JQuery fade-in a div when user scrolls to that div

ForeverNights picture ForeverNights · Mar 20, 2011 · Viewed 23.9k times · Source

An element <div class=""> will fade in when the user scroll down to that div.

I found a solution using a jQuery plugin and another solution to check whether the div is visible on the page. It works.

However, as soon as user scroll to the top of div, it fades in too soon so user doesn't get to see the div fade in. How do I make the div fade-in ONLY if the user scrolls to the bottom of the div so that user can see a nice fade-in effect for the whole div?

Answer

Marcel picture Marcel · Mar 20, 2011

This javascript code is possibly similar to what you currently use, the only difference being the offset used, which is simply the target element's offset().top() + the element's height(). The demo code fades in several <li> elements as the bottom of the elements come into view.

tiles = $("ul#tiles li").fadeTo(0,0);

$(window).scroll(function(d,h) {
    tiles.each(function(i) {
        a = $(this).offset().top + $(this).height();
        b = $(window).scrollTop() + $(window).height();
        if (a < b) $(this).fadeTo(500,1);
    });
});

Demo: jsfiddle.net/Marcel/BP6rq (fullscreen)