Question

I have some jquery code that hides a div when scroll position does not equal 0. This works well however whenever I scroll up and down at the top of the page very fast, or use a go to top of page link, the events seem to bubble up, making the div appear and reappear a few times... is there a way to make it either appear or disappear and never stack the events in order?

I tried stoppropogation() and this did not seem to work. Maybe I was implementing it incorrectly.

    $(window).scroll(
        {
            previousTop: 0
        }, 
        function () {
        var currentTop = $(window).scrollTop();
        if (currentTop == 0) {
            $("#binding-info").fadeIn('slow');
        } else {
            $("#binding-info").fadeOut('slow');
        }
        this.previousTop = currentTop;
    });
Was it helpful?

Solution

That's because jQuery queue animations and fadeIn/fadeOut are animations. Basically, jQuery register what animation should be next and do it when the current animation is done.

To stop that, you can use .stop() before animating the object.

if (currentTop == 0) {
    $("#binding-info").stop().fadeIn('slow');
} else {
    $("#binding-info").stop().fadeOut('slow');
}

But there is a problem with fadeIn. If you do the fadeOut before it reach 1 opacity, it will keep it in data and will not fadeIn to 1 again.

The hot fix would be to use fadeTo():

$("#binding-info").stop().fadeTo('slow', 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top