Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active March 9, 2018 08:26
Show Gist options
  • Save Floofies/b36ca28c45e367d7eec78b12e71029e0 to your computer and use it in GitHub Desktop.
Save Floofies/b36ca28c45e367d7eec78b12e71029e0 to your computer and use it in GitHub Desktop.
Listen for when the URL hash value is changed, and scroll to the first matching Heading element.
// Returns the value of the URL hash parameter, or `null` if the value is empty.
function getHash() {
if (window.location.hash.length < 2) return null;
return window.location.hash.slice(1, window.location.hash.length)
}
const headingSelector = "h1, h2, h3, h4, h5, h6";
// Scrolls to the first Heading element which matches `title`.
function scrollToHeading(title) {
const headings = document.querySelectorAll(headingSelector);
if (headings === null) return;
for (const heading of headings) {
const headingTitle = heading.innerText;
if (headingTitle.length === 0) continue;
if (headingTitle.trim() === title) heading.scrollIntoView();
}
}
// Scrolls to the first Heading element which matches the URL hash value.
function scrollToHash() {
const title = getHash();
if (title === null) return;
scrollToHeading(title);
}
// Listen for when the URL hash value is changed, and scroll to the first matching Heading element.
window.addEventListener("hashchange", scrollToHash);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment