Open and scroll to an anchor link on a different page with an offset to adjust for a fixed header

Here is the script I have used to open and scroll to an anchor link on a different page on a site that has a fixed header and therefore needs to have an offset so the anchor link is not hidden behind the header.

<script>
$(document).ready(function() {
var offsetSize = $(".header").innerHeight();
$("html, body").animate({scrollTop:$(window.location.hash).offset().top-offsetSize }, 500);
});
</script>

What this script is doing is calculating the height of your fixed header (in this case: div.header) and then, upon loading the new page, scrolling to the correct anchor link on the page with an offset that is equal to the height of your fixed header.

In order for this script to work properly, you need to add an ID to your anchor link names that is the same as their name. For example:

<a name="contact" id="contact"></a>
  • Brian

    hey great code it worked perfectly….one thing though i think you are missing hte closing tags for your document ready. The last } i see looks like it is for the .animate….thanks again.

    • http://www.thelibzter.com/ Libby

      thanks for catching that Brian, the post has been updated accordingly :)

  • Michael

    is there any way i can do this without the animating scroll? just jump straight to the anchor? thanks!

  • Tyler Pena

    Just curious, how can we apply return false; to this so the #anchor doesn’t show at the end of URLS?

  • David Rice

    This works great for coming from another page. But if I am already on the page it does not work. For example, I’m on the page “Page 1” with multiple anchors on it. I also have a drop down menu for the multiple anchor tags. If i use the drop down to go to an anchor on the same page, then the adjustment to the fixed header does not happen. Any thoughts on how I might solve this?

  • Parvinder Kumar

    Thanks a lot. Its working properly :)