Skip to content Skip to sidebar Skip to footer

Fade Divs In And Out On Jquery Scroll

I have a few divs which are essentially just colorful rectangles to help visualize. As I scroll down the page, each rectangle should fadeIn or fadeOut depending on scrollbar posit

Solution 1:

You've got a few problems here

One problem problem is is that $(this).position().top is returning 0 for each of the divs (due to their fixed nature). You need to parse the actual css value.

The second is in the nature of the functions fadeIn() and fadeOut(). If you call fadeOut() on an item that is faded out, it will lag behind if one scrolls agressively on your page. But I have not addressed that issue below.

I also put else after the first if because the code paths (should) be mutually exclusive.

$(document).ready(function(){
    var $element_array = $("#content").find("div");
    $(window).scroll(function(){
        $element_array.each (function(){
            if ((parseInt($(this).css('top')) + $(this).height()) < $(window).scrollTop())
                $(this).fadeIn();
            elseif ((parseInt($(this).css('top')) + $(this).height()) > $(window).scrollTop())
                $(this).fadeOut();
        });
    });
});

Solution 2:

Just remove the + height() thing from the fadeOut condition because it makes no sense there

    $(document).ready(function(){
    var remember = 0;
    var $element_array = $("#content").find("div");
    $(window).scroll(function(){

        $element_array.each (function(){
            if (($(this).position().top+ $(this).height()) < $(window).scrollTop()){
                $(this).fadeIn();}
            if (($(this).position().top ) > $(window).scrollTop())
                $(this).fadeOut();
        });

    });
});

http://jsfiddle.net/ruXeq/5/

and it will work like a vanilla ice

Solution 3:

The $(window).scroll() handler is executed for every time you click and scroll down the page, so you are pushing a ton of fadeIn() and fadeOut() calls onto jQuery's animation queue. The solution is to have something in the if statement that is checking whether or not the fade is already happening, and if so prevent adding another animation to the queue, so something roughly like this:

$(document).ready(function(){
    var $element_array = $("#content").find("div");
    var fades = 0;
    $(window).scroll(function(){
        $element_array.each (function(){
            if (($(this).position().top + $(this).height()) < $(window).scrollTop() && (fades == 0))
                $(this).fadeIn(function(){fades = 1;});
            if (($(this).position().top + $(this).height()) > $(window).scrollTop() && (fades > 0))
                $(this).fadeOut(function(){ fades = 0; });
        });
    });
});

http://jsfiddle.net/ruXeq/4/

Post a Comment for "Fade Divs In And Out On Jquery Scroll"