Hellodan
Hellodan

Reputation: 1208

How can I get my div to fade back out with jquery

I'm trying to fade in a div when it scrolls into view from 0.4 to 1 which works fine but I carnt get it to fade back to 0.4 when the user has scrolled past it. How can I get it to do that?

tiles = $("#project_images img").fadeTo(0, 0.4); // set the default image opacity to semi transparent

    $(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(1040,1); // when scrolling down over the image fade it IN.
            if (a > b) $(this).fadeTo(1040, 0.4); // when scrolling down over the image fade it OUT.
        });
    });

Upvotes: 1

Views: 226

Answers (1)

calebds
calebds

Reputation: 26228

Here's one way to implement your requirement. Rather than adapting your logic, I thought about it from the ground up. It boiled down to:

/**
 * on scroll, for each image do the following
 */

var visible    = /** is the image at all visible in the viewport? */ ;
var allVisible = /** is the image totally within the viewport? */ ;

if (visible) {
    if (allVisible) {
        $(this).stop().fadeTo(1040, 1);
    } else {
        $(this).stop().fadeTo(1040, 0.4);
    }
}

jQuery's stop() is used to prevent a buildup of queued fadeTo animations on the images. My code in the demo sacrifices # of calculations for readability, but feel free to swipe it and optimize as you like.

Upvotes: 1

Related Questions