Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Fixed header on scroll

David Carr

Javascript CSS Tutorials

A common web trend is to allow a static header stick to the top of the page when scrolling the page. I imagined there would be quite a bit to it but it turns out it’s very easy to accomplish.

First create a css class, this will set the element to be fixed in place.

.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;

Next add the following jQuery code:

var navpos = $('#header').offset();
$(window).bind('scroll', function() {
  if ($(window).scrollTop() > {
  } else {

This works by created a navpos var that holds the heigh of the element, then using bind on scroll to run a function that determined if the scroll is higher then the height of the element. When that is true give the element a class of navbar-fixed otherwise remove the class.

To see this in action scroll on this blog to see the header move with the page. (Only when running on a normal desktop view so no mobile support.)

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!


My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.