简体   繁体   中英

Is there a way to fire a 'hashchange' event even if the hash is the same?

I have an event listener like this:

window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0));

Then in this handleHashChange function I have some logic for scrolling to an on page element. Taking into account the space it needs to leave for the collapsing/expanding header. If I go to #team from #mission this works fine. The problem is when I click #team twice. Since the hash stays the same it doesn't go in the event listener and falls back to the default browser scroll. I then end up with my header on top of the element, not leaving enough space. Is there a way to overwrite that, too?

Can be jquery or vanilla JS

If you want to force hashchcange event without literaly changing hash you should call: window.dispatchEvent(new HashChangeEvent("hashchange"))

Related question here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM