scroll then snap to top

mediarts picture mediarts · Feb 26, 2011 · Viewed 18.5k times · Source

Just wondering if anyone has an idea as to how I might re-create a nav bar style that I saw a while ago, I just found the site I saw it on, but am not sure how they might have gotten there. Basically want it to scroll with the page then lock to the top...

http://lesscss.org/

Answer

mu is too short picture mu is too short · Feb 26, 2011

Just do a quick "view source" on http://lesscss.org/ and you'll see this:

window.onscroll = function () {
    if (!docked && (menu.offsetTop - scrollTop() < 0)) {
        menu.style.top = 0;
        menu.style.position = 'fixed'; 
        menu.className = 'docked'; 
        docked = true;
    } else if (docked && scrollTop() <= init) { 
        menu.style.position = 'absolute'; 
        menu.style.top = init + 'px';
        menu.className = menu.className.replace('docked', ''); 
        docked = false;  
    }
};

They're binding to the onscroll event for the window, this event is triggered when the window scrolls. The docked flag is set to true when the menu is "locked" to the top of the page, the menu is set to position:fixed at the same time that that flag is set to true. The rest is just some simple "are we about to scroll the menu off the page" and "are we about back where we started" position checking logic.

You have to be careful with onscroll events though, they can fire a lot in rapid succession so your handler needs to be pretty quick and should precompute as much as possible.

In jQuery, it would look pretty much the same:

$(window).scroll(function() {
    // Pretty much the same as what's on lesscss.org
});

You see this sort of thing quite often with the "floating almost fixed position vertical toolbar" things such as those on cracked.com.