Skip to content

Instantly share code, notes, and snippets.

@jaydenseric
Last active August 13, 2020 04:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydenseric/7c8ac07a89fb6b8e7faa22e4808365e6 to your computer and use it in GitHub Desktop.
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.
/**
* 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