Nick
Nick

Reputation: 35

How can I offset scrollTop to take into account the height of a sticky header?

I can just muddle my way through JS/JQuery and I need some help altering this piece of code below. It's being used to scroll the page back to the top of the respective element, however the header for the website is always floating at the top so the top x number of pixels of the element end up underneath the header. How can I edit this so it's offset by the height of the header (static number)?

$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );

Upvotes: 1

Views: 4636

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55623

If your header is a fixed height, just add padding to the top of your page (body) that is equivalent to it's height.

CSS:

body { padding-top: {height_of_header}px; }

If it's not a fixed height, then just change your scrollTop so your page scrolls to the position of your element minus the height of your header:

JS:

$('html, body').animate( { scrollTop: element.offset().top - $('#header').height() }, {duration: 400 } );

Upvotes: 4

Related Questions