user1448485
user1448485

Reputation: 47

On-page anchor tag scroll-to javascript, to land just above destination element

I have a slightly frustrating issue where I have a fixed header on scroll, which has a height of 60px. I use the below code so that when <a href="#some-section"> is clicked, it slides to <div id="some-section">. It works great.

However with the fixed header activated, it means the top 60px of the <div> is cut off.

I'm trying to edit the below javascript so that the scroll lands 60px higher than the top of the related element ID in all cases across the site.

Is that possible at all? I'm guessing it's something to do with offset but can't seem to nail it. Any help greatly appreciated as ever!

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
      if (target.length) {
        $("html, body").animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Upvotes: 0

Views: 77

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337637

You just need to remove 60px from the offset().top of the target element to allow space for the fixed header:

scrollTop: target.offset().top - 60

This could be made more dynamic if you select the fixed header element and get its height directly:

scrollTop: target.offset().top - $('#fixedHeader').height()

Upvotes: 1

Related Questions