Search code examples
javascriptjqueryhtmlscrollanchor

how to catch scroll event caused by hash bang anchor link?


I am just wondering if there's a better way to approach this

So, say you have jump to link using anchor tag:

www.example.com/#about

opening that link will make browser natively auto-scroll to the section with

<div id="about"></div>

now, I want to catch this scroll event, so that I can add more offset on how much scroll the browser should use.

The reason for this is because I have a fixed navigation menu that consumes 120px of the browser.

Regards,


Solution

  • AFAIK there is no way to intercept this behaviour directly i.e. there is no user accessible event associated with it. Instead window.location.hash is made available to you. You can find the associated element and jump to it once the page has loaded.

    e.g. something like:

    function jumpToElement(element, offset) {
      if (!offset) offset = 0;
      var verticalPos = element.offsetHeight;
      window.scrollTo(0, verticalPos + offset);
    }
    function jumpToHash(offset) {
      var hash = window.location.hash;
      // Do nothing if no hash exists
      if (typeof hash !== 'string' || !hash.length) return;
      var targetElement = document.querySelector(hash);
      // Do nothing if targetElement doesn't exist
      if (!targetElement) return;
      jumpToHash(targetElement, offset);
    });
    if (document.readyState === "complete") {
      jumpToHash(-120); // with 120px
    } else {
      document.addEventListener("DOMContentLoaded", jumpToHash);
    }