Make your nav stick to the top of the screen when you scroll past it!

A pretty simple JS include to use when you don’t already have jQuery or the like included on a page.  Just adds a data-nav=”fixed” attribute to your body element that you can style off of via body[data-nav=”fixed”] .whatever {} — this also has the benefit of not hardcoding any styles — you’re free to do it all via your CSS files.

Just remember to swap out ‘nav’ for whatever ID or selector you’ve got on your actual nav.

Potential optimizations would be not using document.getElementById over and over, and just leaving the element cached in a global.  I would advise against caching nav’s offsetTop, though — as it’s possible that things may change in the dom, and that could change!

window.onscroll = function() {
    var d = document,
        nav = d.getElementById( 'nav' ),
        att = ( window.pageYOffset > d.getElementById( 'nav' ).offsetTop ) ? 'fixed' : 'normal';
    d.body.setAttribute( 'data-nav', att );

One Reply to “Make your nav stick to the top of the screen when you scroll past it!”

  1. Hey George. Great script, but the is a little bug in it I have found from trial and error.
    Because you are getting the nav.offsetTop inside the scrolling function, once the data-nav attribute is set to fixed, the offsetTop becomes 0. So the nav won’t reattach to its original position until the user hits the very top of the screen.
    In my version I have moved the variable assignments to outside the scroll function, and assigned an new variable ‘offset’ to the offsetTop value of the nav.

    Please see my code below.

    var d = document,
    nav = d.getElementById(‘nav’),
    offset = nav.offsetTop;
    window.onscroll = function(){
    att = (window.pageYOffset > offset) ? ‘fixed’ : ‘normal’;
    d.body.setAttribute(‘data-nav’, att);

Comments are closed.