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() > navpos.top) {
    $('#header').addClass('navbar-fixed');
  } else {
    $('#header').removeClass('navbar-fixed');
  }
});

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.)

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

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

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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