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.
});
});
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:
jQuery’s
stop()is used to prevent a buildup of queuedfadeToanimations on the images. My code in the demo sacrifices # of calculations for readability, but feel free to swipe it and optimize as you like.