Guest User

Untitled

a guest
Oct 20th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. function anchorLinkHandler(e) {
  2. const distanceToTop = el => Math.floor(el.getBoundingClientRect().top);
  3.  
  4. e.preventDefault();
  5. const targetID = this.getAttribute("href");
  6. const targetAnchor = document.querySelector(targetID);
  7. if (!targetAnchor) return;
  8. const originalTop = distanceToTop(targetAnchor);
  9.  
  10. window.scrollBy({ top: originalTop, left: 0, behavior: "smooth" });
  11.  
  12. const checkIfDone = setInterval(function() {
  13. const atBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2;
  14. if (distanceToTop(targetAnchor) === 0 || atBottom) {
  15. targetAnchor.tabIndex = "-1";
  16. targetAnchor.focus();
  17. window.history.pushState("", "", targetID);
  18. clearInterval(checkIfDone);
  19. }
  20. }, 100);
  21. }
  22.  
  23. const linksToAnchors = document.querySelectorAll('a[href^="#"]');
  24.  
  25. linksToAnchors.forEach(each => (each.onclick = anchorLinkHandler));
Add Comment
Please, Sign In to add comment