TheEarlyMan TheEarlyMan - 1 month ago 8
Javascript Question

Anchor Link Offset doesn't work ONLY on the first click

Below is my JS code. I have a page with anchor links scrolling. I need the user to go to a specific section on the page when the link is clicked, without covering the basic heading of the section.

Here's what I have been able to accomplish (of course, with a bit of help from Stackoverlfow sleuthing).

// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).


The above code seems to work, but the problem is it works only from the second time I click any anchor. Why doesn't it fire on the first tie itself? I know it is related to hashchange, so the javascript is picking up from the second links onwards only because there is a hashchange. Can you give me a solution?

Answer

window.onload=function(){
  
function offsetAnchor() {

    if(location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and m
  }
<a href="#">
  Helo
  </a>

Hope this helps