Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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);
Add Comment
Please, Sign In to add comment