oil-gap
oil-gap

Reputation: 37

Animate HTML element on scroll position

What I would try to do is to animate via CSS3 some HTML when the scrollbar reach a certain position.

I navigated through jQuery plugins founding lots of interesting things such as parallax or harmonic scrolls,and the closest thing I found is the popular lazy load which delay the loading of images while scrolling the page. What I'd like to do is something like that but with animated div or img or a.

I hope somebody can direct me to some good plugins who can help me.

Thanks in advance.

Upvotes: 1

Views: 11609

Answers (3)

martin
martin

Reputation: 832

As commented, you may want to combine the scroll with the actual CSS3 animation (and, further below, eventually the div position while scrolling), which is lacking in the previous answers:

$(window).scroll(function(){
     var top = $(this).scrollTop();
     if(top > 150){
         document.getElementById("some_div_element").style.animationName = "some_animation_name";   
     }
});

A css style property for some_div_element can be initialized with sth else than some_animation_name, hence the animation is triggered once this style property is changed by the scroll position:

div.some_div_element {
   background-color:rgb(140, 20, 20);
   animation-name: undefined_bla;
}

... and used with an animation defition for some_animation_name, e.g.:

@keyframes some_animation_name {
   from {background-color:rgb(140, 20, 20);}
   to {background-color:rgb(200, 20, 20);} 
}

With div elements however, its often not the scroll position itself but the distance of the element to, e.g., the displayed page top that matters to initiate an animation:

window.onscroll = function() {dist_to_top_function()};
function dist_to_top_function() {
   var dist = document.getElementById("some_div_element").getBoundingClientRect().top;
   if(dist < 600){    // distance in px
         document.getElementById("some_div_element").style.animationName = "some_animation_name";          
   }        
}

The js if-statement may also contain modifications on the div style to make them permanently match the end result of the animation, e.g.,

...    
document.getElementById("some_div_element").style.backgroundColor= "rgb(200, 20, 20);";

Upvotes: 0

yckart
yckart

Reputation: 33378

If I understand your needs, you are looking for something like Transe. It allows you to transform and animate elements depeding on the current scroll-offset.

Here's a super simple demo: http://fiddle.jshell.net/ARTsinn/mqcTr/

https://github.com/yckart/jQuery.transe.js/

Another solution is Scrollorama.

Upvotes: 0

sirmdawg
sirmdawg

Reputation: 2579

You'll want to use the jQuery scrollTop() function with the scroll event. Maybe like this:

$(window).scroll(function(){
     var top = $(this).scrollTop();
     if(top > 150){
         //do something after it scrolls down past 150px    
     }
});

Hope this helps :)

Upvotes: 3

Related Questions