Activate animations at specific scroll positions - javascript

I'm creating a CV page, where I included animations - some of them work with additional library: Animate css. It works, but animations start when page is fully loaded - and I want them to happen when scrolled to position where div starts (It's in the middle of page)
I've tried to do that with element .scrollTop, but then I could include value only in px - and i need responsive page ( I use calc() )
There was also possibility that i did something wrong - but i haven't noticed
Just like I said - I want to start animations when div would become in range of sight.

This is possbile, if you combine JQuery with JavaScript DOM or with just JavaScript DOM.
My function might not be the best way, but it works and is fairly simple.
My example starts an Animation when the grey divs Top offset relative to the viewport is lower than 100.
(If you would like to use this make 2 css classes (1 with an animation, 1 without) and set the ID Strings to your HTML Ids)
.Initial{
background-color: #ccc;
color: black;
position: fixed;
}
.AfterScroll{
background-color: #fff;
color: green;
position: fixed;
animation-name: Anim;
animation-duration: 1.4s;
}
#keyframes Anim{
25% {color: red;}
50% {color: blue;}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$( "#AnimationElementID" ).addClass("AfterScroll");
var set = false; // will be false on page load
$( window ).scroll(function() { //On Scroll Event Handler, Could also be window.onscroll (DOM)
// JS HTML DOM get element position relative to viewport
var rect = document.getElementById("AnimationElementTriggerDivID").getBoundingClientRect();
// This is the offset at where your animation would start, 100 = div is 100px from viewport top
if( rect.top <100 && set==false){
$( "#AnimationElementID" ).toggleClass("Initial");
$( "#AnimationElementID" ).toggleClass("AfterScroll");
set=true; // so we only toggle the class once
}
});
</script>
</head>
<body>
<p class="Initial" id="AnimationElementID">
Hi im a text and I will change color if you scroll
</p>
<div id="AnimationElementTriggerDivID" style="background-color: #ccc; position: relative; top:200px; width:20px; height:2000px"> </div>
</body>
</html>
Maybe someone else can provide a better JQuery only option, or a cleaner function, but until then, feel free to use this.
PS: if possible, please provide Code snippets in order for people to be able to help you better and faster.

Related

Fixed layout positions in CSS only as it scrolls up (snap to top)

I am not sure if there is a specific name for the behaviour I want to achieve (in the title).
I'll give an example: on the issues pages on GitHub (e.g. here), where the right column (with information about labels, milestones, assignees) has a fixed position, but only when you scroll down. In other words, it seems to have a static layout as you are scrolling it at first, but then snaps to the top and acts like a fixed layout as you scroll further.
Another example would be how the left and right columns (navigation and contents) on some Google Developer documentation behave in a similar way I have described above.
I hope my question isn't too vague, and although I am aware of position: fixed; in CSS, I am unsure of how to adapt it to achieve the desired effects above.
You can do this by adding and removing classes on scroll with Jquery or javascript I am using jquery here. Also in the following example I added a class to stop the sidebar when it hits the footer but if you just want it to keep going you can remove that part and just keep the sidebar scrolling.
Here is a fiddle Fiddle Demo
I have put this in a full html page so you can just copy and paste it into your text editor so you can see it in action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body{padding: 0;margin: 0;color:#fff;}
header{background: blue;height: 100px;text-align: center;}
footer{background: blue;height: 1000px;text-align: center;}
.content-container{position: relative;}
.main-content{margin-left:200px;background: purple;height: 1000px;text-align:center;}
.sidebar{
position:absolute;
top:0;left:0;
background: green;
height: 200px;
width: 200px;
text-align:center;
/*like to add the following to stop from jumpy scrolling in webkit browsers*/
-webkit-backface-visibility:hidden;
backface-visibility:hidden;
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.sidebar.sidebar-fixed{position:fixed;}
.sidebar.sidebar-stop{position: absolute;bottom:0;top:auto;}
</style>
</head>
<body>
<header>Header</header>
<div class="content-container">
<div class="sidebar">Sidebar</div>
<div class="main-content">Main Content</div>
</div>
<footer>Footer</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
var contentTop = $('.content-container').offset().top;
var sidebarHeight = $('.sidebar').height();
var contentBottom = $('footer').offset().top - sidebarHeight;
$(window).scroll(function(){
var scrolltop = $(this).scrollTop();
//starts the fixed sidebar
if(scrolltop >= contentTop){
$('.sidebar').addClass("sidebar-fixed");
}else{
$('.sidebar').removeClass("sidebar-fixed");
}
//stops the fixed sidebar
if(scrolltop >= contentBottom){
$('.sidebar').addClass("sidebar-stop");
}else{
$('.sidebar').removeClass("sidebar-stop");
}
});
</script>
</body>
</html>
You could try this:
$(window).scroll(function(){
if ($(window).scrollTop() > /* number of pixels from top */){
$("/* sticky div id or class */").css("position", "fixed");
}
});

Creating an overlay page for app

I am looking into adding a single page overlay when a user clicks the "Help" button in a web app I've created. Below is an example of what I want to achieve
I have jquery mobile implemented on my pages with javascript. I looked into the jquery mobile popup panels that overlay a page but it wouldn't serve my purposes.
What resources, libraries, language, etc would I go about doing this? I tried to google but the I get irrelevant results.
I haven't try it, but you can put the background in a div leaving it in behind the classic background (using low css z-index) with a fixed position (absolute position), a fixed width/height (100%/100%) and a trasparency.
When the user click the "Help" buttons you change the z-index putting it on the front of the page.
UPDATE
Assuming a html layout similar like this:
<html>
<head>...</head>
<body>
<div id="container">
<!-- some others divs with the content of the page and the help link -->
HELP
</div>
<div id="over_image"> <!-- add this -->
<img src="path_to_the_overlapping_image" alt="overlap image" />
</div>
</body>
</html>
A default CSS like this
div#container {
z-index: 100;
}
div#over_image {
z-index: -100; // by default the over image is "behind" the page
position: absolute;
top: 0px;
left: 0px;
width: 100%; // or puts the width/height of the "screen" in pixels
height: 100%;
}
div#over_image img {
width: 100%;
height: 100%;
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
And at the end the jQuery function
$("a#help_button").on("click", function(event){
event.preventDefault(); // it's not really a link
$("div#over_image").css("z-index", "1000");
})
You should implement the "hide" function too, to "reset" the overlapping image on some action, maybe something like this:
$("div#over_image img").on("click", function(){
// when the user click on the overlap image, it disappears
$("div#over_image").css("z-index", "-100");
})
I haven't try it, maybe there are some more little things to change to make it works correctly, but it is a good begin.
SOME REFERENCES
Opacity / transparency: http://www.w3schools.com/css/css_image_transparency.asp
jQuery css: http://api.jquery.com/css/

Fire CSS3 Transform from Javascript button click

I am new to CSS3 transitions. I am trying to make a image slideshow for webkit only. there are 3 images aligned next to each other inside a wide DIV. This wide DIV is inside a container DIV whoose overflow property has been set as hidden. the width of the container DIV is equal to each Image, hence user can see only one image at a time.
here is the HTML and CSS for that.
HTML
<div id = "imageHolder">
<div id="slide1_images">
<img src="./images/fish.jpg" />
<img src="./images/desert.jpg" />
<img src="./images/space.jpg" />
</div>
</div>
CSS
#imageHolder
{
width: 320px;
height: 240px;
border: 1px solid grey;
overflow: hidden;
position: relative;
}
#slide1_images
{
position:absolute;
left:0px;
width:960px;
-webkit-transition: -webkit-transform 0.5s;
}
Now I have added a CSS hover selector in the code just to test the transition. when user hovers over the image (the inner DIV, to be precise), the whole set moves to left by 320 pixels (which is the width of each image).
CSS for hover
#slide1_images:hover
{
-webkit-transform:translate(-320px,0);
}
Upto this the code works perfectly, when I hover mouse over the first image, the set moves left and the 2nd image fits perfectly in the outer DIV.
What I want is, to perform the same action on Javascript button click. I have added a button called btnNext in my page. How can I fire the translate from the button click event? I tried the below but it does not work.
Javascript
<script type = "text/javascript">
function btnNext_clicked()
{
document.getElementById("slide1_images").style.-webkit-transform = "translate(-320px,0)"
}
</script>
I am sure I have done something stupid! could you please help me out fixing the Javascript function? Thanks a lot in advance :)
With the obvious caveat its for webkit browsers only you just need to use
.style["-webkit-transform"] = ..
as - cannot be used in an inline propery name here: style.-webkit-transform
From JavaScript you can access -webkit-transform property in this way:
var style = document.getElementById("slide1_images").style;
style.webkitTransform ='translateX(-320px)';
You can make it cross-browser friendly by accessing following properties:
transform
webkitTransform
MozTransform
OTransform
msTransform

How to make a div fade in after a specific height?

I am trying to make a fixed div appear after the user scrolls 100px down on a page, and disappears again when the scroll past that 100px to the top.
I would like to use a opacity fade transition of 0.5s when the div appears to make a nice transition.
Have been trying to do this but can only seem to get it to appear as soon as the user scrolls using this code:
Would love to hear from someone who has the solution.
Thanks! :)
Here is a start http://jsfiddle.net/ZtGK6/
$(window).scroll(function(){
if($(window).scrollTop()>100){
$("#theDiv").fadeIn();
}else{
$("#theDiv").fadeOut();
}
});
A good way to make it hide on page load is to give the surrounding div CSS class a display: none; property. That way it will display hidden when the page initially loads, and not fade out quickly upon page load. Then, your JavaScript will load it after you scroll down the determined # of pixels. This will behave cleanly and is super easy to achieve.
HTML:
<div id="theDiv">Now I'm visible</div>
CSS:
body, html {
height: 200%;
}
#theDiv{
top: 30px;
left: 20px;
display: none;
background-color:#FFF000;
width:200px;
height:200px;
}
Javascript:
$(window).scroll(function(){
if($(window).scrollTop()>100){
$("#theDiv").fadeIn();
}else{
$("#theDiv").fadeOut();
}
});
Demo: http://jsfiddle.net/waitinforatrain/ZtGK6/3/
$(function() {
var theDiv = $('#myDiv'),
scrollPos = $('body').scrollTop();
if ( scrollPos > 100 ) {
theDiv.fadeIn(500); // 500 milliseconds
} else {
theDiv.fadeOut(500);
}
});
I haven't been able to test this and you may have to put the if statement in a scroll event so the scrollPos var updates as you scroll.

Change div height onclick with animation

I'm trying to make a gallery using divs that change their height when you click on them. Ideally, this would include animation to smoothly expand the div's height. There will be several of each div on each page, so it needs to just expand that section.
It's actually supposed to turn out something like the news section on this page: http://runescape.com/
I'd like to do it with JavaScript/jQuery if possible.
$('div').click(function(){
$(this).animate({height:'300'})
})
Check working example at http://jsfiddle.net/tJugd/
Here's the code I ended up using:
JS:
document.getElementById("box").addEventListener("click", function() {
this.classList.toggle("is-active");
});
CSS:
#box {
background: red;
height: 100px;
transition: height 300ms;
width: 100px;
}
#box.is-active {
height: 300px;
}
HTML:
<div id="box"></div>
Fiddle:
https://jsfiddle.net/cp7uf8fg/
try
$('div').toggle(function(){
$(this).animate({'height': '100px'}, 100);
}, function(){
$(this).animate({'height': '80px'}, 100);
});
DEMO
jQuery rules. Check this out.
http://api.jquery.com/resize/
The complete solution:
Both spacer DIV and Margin or Padding on content DIV works but best to still have a spacer DIV.
Responsive design can be then applied to it in your CSS file.
This is mutch better as with JAVA the screen would flicker!
If you use a grid system there will be a media query part there you need to include your settings.
I use a little spacer on HD screen while its increasing till mobile screen!
Still if you have breadcrumb in header multiple lines can be tricky, so best to have a java but deferred for speed resons.
Note that animation is for getting rid of flickering of screen.
This java then would only fire if breadcrumb is very long otherwise single CSS applied via the grid and no flickering at all.
Even if java fired its doing its work via an elegant animation
var header_height = $('#fixed_header_div').height();
var spacer_height = $('#header_spacer').height() + 5;
if (header_height > spacer_height) {
$('#header_spacer').animate({height:header_height});
};
Note that I have applied a 5px tolerance margin!
Ho this helps :-)
I know this is old, but if anyone seems to find their way here. #JacobTheDev answer is great and has no jQuery! I have added a little more for use cases where the event is not being assigned at the same point your toggling the css class.
HTML
<div id='item' onclick='handleToggle()'> </div>
JS
handleToggle(event){
document.getElementById(event.target.id).classList.toggle('active')
}
CSS
#item {
height: 20px;
transition: 1s;
}
.active {
height: 100px;
}

Categories