Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a navigation which disappears while scrolling down but shows up by scrolling up? [closed]

I want to create a navigation bar that disappears when the user scrolls down the page but reappears when the user scrolls back up. Kind of like the search bar that is in the mobile chrome app. Does anyone know how to do so? All I have so far is a simple div that is fixed to the top.

Here is an example - the navigtion only appears when the user scrolls up a little bit.

like image 459
Zach Starnes Avatar asked Jun 16 '13 18:06

Zach Starnes


1 Answers

Prototype using jQuery

Here is one way you might do this.

Suppose this your HTML, fixed header and some content:

<div class="header">The header or navigation elements go here...</div>
<div class="main">
    <p>Some content...</p>
</div>

Your CSS might be:

.header {
    position: fixed;
    top: 0px;
    left: 9px;
    right: 9px;
    height: 50px;
    border: 1px dotted blue;
    background-color: rgba(125, 125, 125, 0.5);
}
.main {
    margin-top: 60px;
    border: 1px solid blue;
    width: 25%;
}

The jQuery to make this happen is as follows:

$(window).scroll(
    {
        previousTop: 0
    }, 
    function () {
    var currentTop = $(window).scrollTop();
    if (currentTop < this.previousTop) {
        $(".sidebar em").text("Up"); /* optional for demo */
        $(".header").show();
    } else {
        $(".sidebar em").text("Down");
        $(".header").hide();
    }
    this.previousTop = currentTop;
});

Demo fiddle: http://jsfiddle.net/audetwebdesign/Mar62/

How This Works

The trick is to compute whether your are scrolling up or scrolling down. You can do this by storing the previous value of the .scrollTop position.

Define an anonymous JavaScript object with a single member to store the value:

    {
        previousTop: 0
    }

and pass that object to the jQuery .scroll() function.

When the window scrolls, get the current top position of the window scroll bar,
then compare it to the previous value, and then either show the header if scrolling up or hide it if scrolling down.

After the show/hide decision, update the .previoustop with the currentTop value.

No other plug in required. You can fade in/out the header or use some other animation instead of a simple show/hide.

like image 152
Marc Audet Avatar answered Oct 03 '22 02:10

Marc Audet