Last active
August 13, 2020 04:13
-
-
Save jaydenseric/7c8ac07a89fb6b8e7faa22e4808365e6 to your computer and use it in GitHub Desktop.
A JavaScript function to clear the browser location hash (if present), without leaving a `#` on the end of the URL, affecting page scroll, or causing the page to reload, whilst allowing `hashchange` events to work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Clears the window location hash (if present), without leaving a `#` on the | |
* end of the URL, affecting page scroll, or causing the page to reload, whilst | |
* allowing `hashchange` events to work. Only usable in a browser environment. | |
* | |
* Note: It’s debatable if a `hashchange` event should be fired when the old | |
* URL has an empty `#` on the end, since `window.location.hash` will be the | |
* same before and after; an empty string. This should be ok though as a native | |
* link with `href="#"` triggers `hashchange` when the old URL has no hash. | |
* @see [GitHub gist](https://gist.github.com/jaydenseric/7c8ac07a89fb6b8e7faa22e4808365e6). | |
*/ | |
export default function clearLocationHash() { | |
const oldURL = window.location.href; | |
const hashIndex = oldURL.indexOf('#'); | |
if (hashIndex !== -1) { | |
const newURL = oldURL.substring(0, hashIndex); | |
window.history.pushState(null, null, newURL); | |
window.dispatchEvent( | |
new HashChangeEvent('hashchange', { oldURL, newURL }) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment