Search code examples
jqueryhtmlcssjquery-animatefadein

jQuery scroll to fadein and animate simultaneously on div


I have been trying to get this jQuery correct, but I just can't seem to get it right. What I am trying to do is have a user scroll, and when they scroll to the corresponding pixel limit, jquery fadein and animate will occur, creating a cool little effect. I was trying to use fadeIn, but it didn't work simultaneously, so I am using css. The problem is that while I have it working, when I continue to scroll, the images continue to flicker off and on.

Here is the my code.

    $(window).bind("scroll", function() {
    if ($(this).scrollTop() > 560 ) {
        $('#subOverlay').css({'display':'block', 'opacity':'0'})
        .animate({'opacity':'1','left':'25%'}, 1500);
    } else {
        $("#subOverlay").stop().fadeOut();
    }
});

You will notice in my code above, I want the user to scroll to 560 pixels, and then have the effects work simultaneously. I have tried to correct this "flickering" but I just can't get it. I have tried using .fadeIn(1000).animate({'opacity':'1','left':'25%'}, 1500); but it doesn't create the effect I am trying to achieve simultaneously.

Please see the JSFIDDLE for an example of what I am talking about. Can you help? Or point me in the right direction? Thank you.


Solution

  • As much as possible, try to avoid using jQuery for CSS work. This includes css, animate, fadeOut, etc. Here's an example, where the JavaScript only toggles classes:

    http://jsfiddle.net/05Leto4e/1/