Demchar
Demchar

Reputation: 13

JavaScript hide div element on scroll action

I'm using this bit of code to hide a menu bar when users scroll on a page. It works fine on Chrome 17.0.963.78 but keeps on flickering in and out on other browsers, namely I.E. firefox and safari ..

$(window).load(function(){
    $(document).scroll(function(){  
        $('#inner_floating').fadeOut();

        var scrollA = $('body').scrollTop();

        setTimeout(function(){
            if(scrollA == $('body').scrollTop()){
                $('#inner_floating').fadeIn();
            }
        }, 100);
    })
});

Upvotes: 0

Views: 1306

Answers (1)

gavinblair
gavinblair

Reputation: 386

The problem is that your .scroll function is being called for every pixel (or mousewheel tick) scrolled, so the animations are being run many times consecutively.

Try something like this:

$(window).load(function(){
    $(document).scroll(function(){  
        if($("#inner_floating:hidden").length == 0) {
            $('#inner_floating').fadeOut();
        }

        var scrollA = $('body').scrollTop();

        setTimeout(function(){
            if(scrollA == $('body').scrollTop() && $("#inner_floating:hidden").length > 0){
                $('#inner_floating').fadeIn();
            }
        }, 100);
    })
});

This way the animation is only happening if necessary.

Upvotes: 1

Related Questions