Skip to content
OSULZER.AT
Code1 min read· updated June 15, 2023

ScrollOffset for Anchor Links in JavaScript (jQuery)

With a fixed header, anchor links scroll the target out of view. This jQuery snippet adds a site-wide scroll offset based on the header height plus 20px.

Below is a handy JavaScript widget that lets you define a site-wide scroll offset for anchor links. This means that when you click an anchor link, the browser does not land pixel-perfect at the start of the target element but stops a few pixels before it. This is useful if, for example, you use a fixed header. In the snippet, the height of the offset is derived from the height of the header, plus 20px. You will still need to define the header container in the code yourself.

    $(function() {


        headerScrollOffset = $('#masthead').height() + 20;
     
        
        $('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 - headerScrollOffset
                }, 200);
                return false;
              }
            }
          });
        });

Photo by Lucas Sankey on Unsplash

PHP Freelancer

Prefer to have it done for you?

Customizations, plugins, and integrations - cleanly implemented, €120/h plus VAT.

See the PHP freelancer

New project?

Contact.

Tell me briefly about your project - I'll get back to you personally.

Your data is used solely to handle your inquiry. More in the privacy policy.