Create sticky header

On this template: https://p.w3layouts.com/demos/humanity/web/
There is a header that contains a logo (Humanity) and menu: class=header
There is a colored bar above it: class=head

I want the header div to be sticky when the page scrolls. The head div should disappear when the page is scrolled down.

What changes do I need to make to the css and/or javascript to make this happen?
LVL 26
Eddie ShipmanAll-around developerAsked:
Who is Participating?
 
Julian HansenCommented:
Add this CSS class
 .header.sticky {
  position: fixed;
  top: 0;
  background-color: white;
  width: 100%;
  z-index: 100; 
}

Open in new window

Add this jQuery
$(function() {
  var headerTop = $('.header').offset().top;
  $(window).on('scroll',function(){
    var scrollTop = $(window).scrollTop();
    if (scrollTop >= headerTop) {
      $('.header').addClass('sticky');
    }
    else {
      $('.header').removeClass('sticky');
    }
});
})

Open in new window

0
 
Eddie ShipmanAll-around developerAuthor Commented:
I also  set the image to another height but thanks, Julian.
0
 
Julian HansenCommented:
You are welcome.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.