Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a Div when the scroll bar is moving with jQuery?

I just want the #menu to fade when the scroll bar is moving to provide a less cluttered interface. Is there code that would allow this?

I guess basically what I'm looking for is how to grab the scroll bar movement event. To slowly fade out the #menu after 1 seconds of scrolling and bring back the #menu after 2 second of scroll-bar inactivity.

Thank you so much!

like image 528
Mohammad Avatar asked Sep 12 '11 16:09

Mohammad


1 Answers

var $menu = $("#menu");
var opacity = $menu.css("opacity");
var scrollStopped;

var fadeInCallback = function () {
    if (typeof scrollStopped != 'undefined') {
        clearInterval(scrollStopped);
    }

    scrollStopped = setTimeout(function () {
        $menu.animate({ opacity: 1 }, "slow");
    }, 2000);
};

$(window).scroll(function () {
    if (!$menu.is(":animated") && opacity == 1) {
        $menu.animate({ opacity: 0 }, "slow", fadeInCallback);
    } else {
        fadeInCallback.call(this);
    }
});

http://jsfiddle.net/zsnfb/9/

This sets the scroll event to do a few things. First it clears a timeout to fade the menu div back in. After that, if the menu isn't already faded out, it fades the menu out and sets the timeout in the callback. If the menu is already faded out, it just sets the timeout. If the user stops scrolling, the menu will fade back in after 2 seconds.

There are other solutions that use fadeOut() and fadeIn(). My only issue with those functions in this case is that setting display: none; to the menu div will affect the layout of the page, where setting visibility: hidden; or opacity: 0; shouldn't affect the layout.

like image 96
btleffler Avatar answered Oct 28 '22 10:10

btleffler