Search code examples
javascriptjquerycssfade

div fade out inner div elements


I came accross the following fiddle which let elements fade out of the document 1 by 1 as they reach the top.

By executing javascript:

$(window).scroll(function () {
    $('[id^="box"]').each(function () {
        if (($(this).offset().top - $(window).scrollTop()) < 20) {
            $(this).stop().fadeTo(100, 0);
        } else {
            $(this).stop().fadeTo('fast', 1);
        }
    });
});

http://jsfiddle.net/JdbhV/6/

Only this is working on the full window, I want it to work on a div tag. So I modified the fiddle to add the div test and all other divs inside there, then modify the javascript to grab the div instead of the window:

$("#test").scroll(function () {
    $('[id^="box"]').each(function () {
        if (($(this).offset().top - $("#test").scrollTop()) < 20) {
            $(this).stop().fadeTo(100, 0);
        } else {
            $(this).stop().fadeTo('fast', 1);
        }
    });
});

http://jsfiddle.net/JdbhV/1692/

But now they fade too fast and not when they reach the top of the div.

Does someone have a pointer what is going wrong here?


Solution

  • The .offset() method allows us to retrieve the current position of an element relative to the document.

    Scrolling the window doesn't change the position of elements in the document however scrolling elements inside another element does. This causes the offset position to change which throws off the check to see if box is at the top of the scroll view.

    Try using the .position() method which gets the position relative to the parent.

    $("#test").scroll(function () {
        $('[id^="box"]').each(function () {
                //When the top of the square goes above the top of the scroll element, fade it out
            if ($(this).position().top < 0) {
                $(this).stop().fadeTo(100, 0);
            } else {
                $(this).stop().fadeTo('fast', 1);
            }
        });
    });
    

    http://jsfiddle.net/ys0m6axL/