Guest User

Untitled

a guest
Mar 18th, 2018
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. // Returns the value of the URL hash parameter, or `null` if the value is empty.
  2. function getHash() {
  3. if (window.location.hash.length < 2) return null;
  4. return window.location.hash.slice(1, window.location.hash.length)
  5. }
  6. const headingSelector = "h1, h2, h3, h4, h5, h6";
  7. // Scrolls to the first Heading element which matches `title`.
  8. function scrollToHeading(title) {
  9. const headings = document.querySelectorAll(headingSelector);
  10. if (headings === null) return;
  11. for (const heading of headings) {
  12. const headingTitle = heading.innerText;
  13. if (headingTitle.length === 0) continue;
  14. if (headingTitle.trim() === title) heading.scrollIntoView();
  15. }
  16. }
  17. // Scrolls to the first Heading element which matches the URL hash value.
  18. function scrollToHash() {
  19. const title = getHash();
  20. if (title === null) return;
  21. scrollToHeading(title);
  22. }
  23. // Listen for when the URL hash value is changed, and scroll to the first matching Heading element.
  24. window.addEventListener("hashchange", scrollToHash);
Add Comment
Please, Sign In to add comment