Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 339
ForeverNights Avatar asked Mar 20 '11 09:03

ForeverNights


2 Answers

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)

like image 135
Marcel Avatar answered Oct 31 '22 19:10

Marcel


you mentioned that you used a jQuery plugin, i don't know if you have tried jQuery waypoints plugin, you can do it using this plugin easily by passing an offset option to the plugin as follows:

// by default your element will be hidden
$('div').hide();
// call waypoint plugin
$('div').waypoint(function(event, direction) {
    // do your fade in here
    $(this).fadeIn();
}, {
   offset: function() {
       // The bottom of the element is in view
       return $.waypoints('viewportHeight') - $(this).outerHeight();
    }
});

offset : Determines how far the top of the element must be from the top of the browser window to trigger a waypoint. It can be a number, which is taken as a number of pixels, a string representing a percentage of the viewport height, or a function that will return a number of pixels.

so on the previous example, your div won't fade in unless it's in the middle of the page.

like image 28
Anas Nakawa Avatar answered Oct 31 '22 19:10

Anas Nakawa