Sticky Nav After Scroll – Olly McTwist 580

Posted on: April 1st, 2014

There are many different ways to go about getting a navigation stick to the top of your page. If you’re using a framework like bootstrap or Foundation you could just add an extra class and it will stick to the top.

Note: There are no skateboard tricks in this post, sorry for that totes linkbait title brah.

Same goes for if you want to have it start at a certain place on the page and then stick if you scroll past it. While that’s all well and good and frameworks have their time and place, what about those of us who aren’t using frameworks? Have no fear, because I found a way to do it in less than 9 lines of CSS and JavaScript. Is this the best way to do it? Not sure. Does it work? Yes.

  var $window = $(window),
      $stickyEl = $('#inner-header'),
      elTop = $stickyEl.offset().top;

  $window.scroll(function() {
     $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
  });

.sticky {
  position: fixed;
  top: 0;
  z-index: 111;
}

In the above code we are naming the sticky element, #inner-header, and then defining how far from the top of the page it is located. Using offset() in this context helps “Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.” Because we’ve defined the top element as the one we’d like to get, we can now use it in reference to the rest of the page.

When a user has scrolled past the point of the initial element offset, a class of “sticky” will be added to the element. Likewise, if we scroll back up to a spot before the offset, the #inner-header will have the class of “sticky” removed.

I’ve not used this type of functionality before, so it opens up a lot of different options in terms of CSS3. By setting transitions to #inner-header we can prepare it to smoothly transition into a new shape, or place when .sticky gets added.

As always, if you’ve got a better way to do this, feel free to put that down in the comments.

previous post: Using Font Awesome Pretty Much Anywhere next post: WordPress Breadcrumbs – Jankified