Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to keep a DIV at the top of the screen AND restore its position after scrolling up (and reaching its original position)

Tags:

jquery

scroll

I want a div element to do something similar to gmail.

  • When scrolling down, once gmail's menu (Archive, Spam, Delete...etc) reaches the the top of the screen, it stays there.

  • When scrolling up, the menu returns to it's original position.

Another sample is the side bar of this page: sample 2

How to achieve that with a simple (and easy to understand) jQuery code? (Compatible with all browsers)

<div id="header">Menu goes here =)</div>
like image 508
Omar Avatar asked Oct 13 '11 22:10

Omar


1 Answers

Specific to your problem, try this:

CSS:

#header.floating {
    position: fixed;
    top: 0;
}

JavaScript:

$(document).ready( function() {

    $(window).scroll( function() {
        if ($(window).scrollTop() > $('#header-wrapper').offset().top)
            $('#header').addClass('floating');
        else
            $('#header').removeClass('floating');
    } );

} );

jsFiddle: http://jsfiddle.net/omarjuvera/0p9p43Lz/

like image 193
Matt Bradley Avatar answered Sep 28 '22 06:09

Matt Bradley