Skip to content Skip to sidebar Skip to footer

How To Make A Navigation Which Disappears While Scrolling Down But Shows Up By Scrolling Up?

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

Solution 1:

Prototype using jQuery

Here is one way you might do this.

Suppose this your HTML, fixed header and some content:

<divclass="header">The header or navigation elements go here...</div><divclass="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.

Solution 2:

you mean like g+ does it ?

you can use this plugin here ( https://github.com/brandonaaron/jquery-mousewheel ) to detect the mousewheel event and take action based on that

$('#my_elem').mousewheel(function(event, delta, deltaX, deltaY) {
    console.log(delta, deltaX, deltaY);
});

there is also a test page here

Post a Comment for "How To Make A Navigation Which Disappears While Scrolling Down But Shows Up By Scrolling Up?"