Wikipedia Smooth Scroll

Adds smooth scrolling for in-page links on Wikipedia and sister sites

  1. // ==UserScript==
  2. // @name Wikipedia Smooth Scroll
  3. // @description Adds smooth scrolling for in-page links on Wikipedia and sister sites
  4. // @version 0.2
  5. // @author Daniel Bronshtein
  6. // @license MIT
  7. // @homepage https://github.com/DaniBr/wikipedia-smooth-scroll
  8. // @grant none
  9. // @run-at document-idle
  10. // @match https://*.wikipedia.org/wiki/*
  11. // @match https://*.wiktionary.org/wiki/*
  12. // @match https://*.wikibooks.org/wiki/*
  13. // @match https://*.wikiquote.org/wiki/*
  14. // @match https://*.wikivoyage.org/wiki/*
  15. // @match https://*.wikisource.org/wiki/*
  16. // @match https://*.wikinews.org/wiki/*
  17. // @match https://*.wikiversity.org/wiki/*
  18. // @match https://*.wikifunctions.org/wiki/*
  19. // @namespace https://greasyfork.org/users/1450663
  20. // ==/UserScript==
  21. (function(){
  22. function scrollSmoothlyTo(element) {
  23. element.scrollIntoView({
  24. behavior: 'smooth'
  25. })
  26. }
  27. function getIdFromInternalLink(link) {
  28. try {
  29. return decodeURIComponent(link.getAttribute('href').substring(1))
  30. } catch (e) {
  31. return link.getAttribute('href').substring(1)
  32. }
  33. }
  34. function handleInternalLinkClick(event) {
  35. const link = event.currentTarget
  36. const id = getIdFromInternalLink(link)
  37. const element = document.getElementById(id)
  38. if (!element) return
  39. scrollSmoothlyTo(element)
  40. history.pushState({ scrollTo: id }, '', link.href)
  41. event.preventDefault()
  42. }
  43. document.querySelectorAll("a[href^='#']").forEach(link => {
  44. link.addEventListener('click', handleInternalLinkClick)
  45. })
  46. //ToDo: add smooth scrolling on popstate (when navigating back and forward)
  47. })()