Jacob Harrison
Jacob Harrison

Reputation: 27

Fix header based on scrolling 100% of the height

So I currently have my fixed header working on scroll, however I have a set height in the jQuery for the size of the header. Now the height of this header can vary, so rather than doing it on scroll of say 105px, how could I do it on scroll of 100% of the height? Because of the fact the header can change, the current code will cause the fixed header not to work as smoothly on certain clients pages.

$(window).scroll(function(){            
  if ($(window).scrollTop() >= 105) {
    $('#navigation').addClass('fixed-header');
   }
  else {
    $('#navigation').removeClass('fixed-header');
   }
    });

So this code does work as stated. The issue is that it is set to '105'. I need this to change dependent on the size of the header. Rather than being set to a certain size all the time.

Upvotes: 0

Views: 306

Answers (1)

mcfly24
mcfly24

Reputation: 64

You have to get that header height.

Let's say that header is

<header>stuff</header>

in JS

const header = $("header");

$(window).scroll(function(){            
  if ($(window).scrollTop() >= header.height()) {
    $('#navigation').addClass('fixed-header');
   }
  else {
    $('#navigation').removeClass('fixed-header');
   }
    });

Read about element.height(); here

Upvotes: 1

Related Questions