noiseymur
noiseymur

Reputation: 876

Prevent jumping to hash on initial load of URL consisting a hash

It is possible to prevent jumping to hash when hash changes with the following function for example:

function handleHashChange() {
   const scrollY = window.pageYOffset;
   window.scrollTo({top: scrollY});
}

But this only works if the hash is changed later. When a page with a URL that already consists a hash is loaded, this does not work. (For example: mysite.com/posts/#popular) I guess maybe because native hashchange event is sent to Callback Queue before custom hashchange event listener is added.

Is there any workaround to this problem ?

Upvotes: 0

Views: 342

Answers (1)

noiseymur
noiseymur

Reputation: 876

So, it appears that, all that needs to be done is calling that scroll function inside load event listener:

window.addEventListener('load',()=>{
    const scrollY = window.pageYOffset;
      setTimeout(() => {
        window.scrollTo({top: scrollY});
      }, 0);
  });

Upvotes: 0

Related Questions