Smooth Scroll to Anchor Vanilla JS

Smooth Scroll to Anchor Vanilla JS
Code Snippet:Smooth scrolling to anchor with pure javascript
Author: AciD
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 3,069
License: MIT
Edit Code online: View on CodePen
Read More

This Vanilla JS code snippet helps you to create a smooth scroll to anchor. It smoothly jumps to the section while clicking on the hash anchor. You can use this to create a table of contents or reference section.

How to Create Smooth Scroll to Anchor Vanilla JS

1. First of all, create the HTML structure as follows:

  1. <div class="container">
  2. <div class="filler anchor" id="anchor1">anchor1</div>
  3. <div class="links">
  4. <a id="anchor1Link" href="#anchor1">Anchor 1</a>
  5. <a id="anchor2Link" href="#anchor2">Anchor 2</a>
  6. <a id="anchor3Link" href="#anchor3">Anchor 3</a>
  7. <a id="anchor4Link" href="#anchor4">Anchor 4</a>
  8. </div>
  9. <div class="longText">
  10. <p id="anchor2" class="anchor">anchor2 : This is a line, and there will be more after me.</p>
  11. <p id="anchor3" class="anchor">anchor3 : This is a line, and there will be more after me.</p>
  12. <p id="anchor4" class="anchor">anchor4 : This is a line, and there will be more after me.</p>
  13. </div>
  14. <div class="links">
  15. <a id="anchor1Link2" href="#anchor1">Anchor 1</a>
  16. <a id="anchor2Link2" href="#anchor2">Anchor 2</a>
  17. <a id="anchor3Link2" href="#anchor3">Anchor 3</a>
  18. <a id="anchor4Link2" href="#anchor4">Anchor 4</a>
  19. </div>
  20. <div class="filler"></div>
  21. </div>

2. After that, add the following CSS styles to your project:

  1. .links {
  2. margin-top: 0.5rem;
  3. margin-bottom: 2rem;
  4. }
  5. .links a {
  6. font-size: 1.4rem;
  7. color: #006080;
  8. text-decoration: none;
  9. transition: color 0.5s ease, border-bottom 0.5s ease;
  10. border-bottom: 2px solid transparent;
  11. }
  12. .links a:hover {
  13. color: #646415;
  14. border-bottom: 2px solid yellow;
  15. }
  16. .links a:not(:last-of-type) {
  17. margin-right: 2rem;
  18. }
  19.  
  20. .longText > p:last-of-type:after {
  21. content: "...or not ;)";
  22. }
  23.  
  24. .anchor {
  25. color: lime;
  26. font-weight: bold;
  27. }
  28.  
  29. p {
  30. margin: 0;
  31. text-align: center;
  32. }
  33.  
  34. .container {
  35. display: flex;
  36. flex-direction: column;
  37. justify-content: center;
  38. align-items: center;
  39. }
  40.  
  41. a.button {
  42. color: yellow;
  43. text-decoration: none;
  44. transition: color 0.3s ease;
  45. }
  46. a.button:focus {
  47. outline: none;
  48. }
  49. a.button:hover {
  50. color: lime;
  51. }
  52.  
  53. .button2 {
  54. background-color: deeppink;
  55. color: white;
  56. border: 1px solid red;
  57. border-radius: 2px;
  58. height: 30px;
  59. cursor: pointer;
  60. outline: none;
  61. }
  62. .button2:focus, .button2:active {
  63. outline: none;
  64. }

3. Finally, add the following JavaScript code and done.

  1. (function () {
  2. let d = document;
  3.  
  4. function init() {
  5. //Links
  6. let anchor1Link = d.getElementById('anchor1Link');
  7. let anchor2Link = d.getElementById('anchor2Link');
  8. let anchor3Link = d.getElementById('anchor3Link');
  9. let anchor4Link = d.getElementById('anchor4Link');
  10. let anchor1Link2 = d.getElementById('anchor1Link2');
  11. let anchor2Link2 = d.getElementById('anchor2Link2');
  12. let anchor3Link2 = d.getElementById('anchor3Link2');
  13. let anchor4Link2 = d.getElementById('anchor4Link2');
  14. //Anchors
  15. let anchor1 = d.getElementById('anchor1');
  16. let anchor2 = d.getElementById('anchor2');
  17. let anchor3 = d.getElementById('anchor3');
  18. let anchor4 = d.getElementById('anchor4');
  19.  
  20. anchor1Link.addEventListener('click', e => {scrollTo(anchor1, e);}, false);
  21. anchor1Link2.addEventListener('click', e => {scrollTo(anchor1, e);}, false);
  22. anchor2Link.addEventListener('click', e => {scrollTo(anchor2, e);}, false);
  23. anchor2Link2.addEventListener('click', e => {scrollTo(anchor2, e);}, false);
  24. // anchor2Link.onclick = function() { scrollToSimple(document.documentElement, 500, 3000); }
  25. // anchor2Link2.onclick = function() { scrollToSimple(document.documentElement, 0, 3000); }
  26. anchor3Link.addEventListener('click', e => {scrollTo(anchor3, e);}, false);
  27. anchor3Link2.addEventListener('click', e => {scrollTo(anchor3, e);}, false);
  28. anchor4Link.addEventListener('click', e => {scrollTo(anchor4.offsetTop, e);}, false);
  29. anchor4Link2.addEventListener('click', e => {scrollTo(anchor4.offsetTop, e);}, false);
  30.  
  31. console.log(anchor2); //DEBUG
  32. console.log('anchor1: ' + scrollTopValue(anchor1) + ' / ' + offsetTopValue(anchor1)); //DEBUG
  33. console.log('anchor2: ' + scrollTopValue(anchor2) + ' / ' + offsetTopValue(anchor2)); //DEBUG
  34. console.log('anchor3: ' + scrollTopValue(anchor3) + ' / ' + offsetTopValue(anchor3)); //DEBUG
  35. console.log('anchor4: ' + scrollTopValue(anchor4) + ' / ' + offsetTopValue(anchor4)); //DEBUG
  36. // d.addEventListener('scroll', (e) => { console.log(e) }, false); //DEBUG
  37.  
  38. console.log('App loaded. Have fun!');
  39. }
  40.  
  41. function scrollTopValue(domElement) {//DEBUG
  42. return 'scrollTopValue:', domElement.scrollTop;
  43. }
  44. function offsetTopValue(domElement) {//DEBUG
  45. return 'offsetTopValue:', domElement.offsetTop;
  46. }
  47.  
  48. /*function scrollToSimple(element, to, duration) { //FIXME finish this
  49. if (duration < 0) return;
  50. var difference = to - element.offsetTop;
  51. var perTick = difference / duration * 10;
  52. console.log('perTick', perTick); //DEBUG
  53. setTimeout(function() {
  54. console.log('element.scrollTop:', element.scrollTop); //DEBUG
  55. element.scrollTop += perTick;
  56. console.log('element.scrollTop:', element.scrollTop); //DEBUG
  57. scrollTo(element, to, duration - 10);
  58. }, 10);
  59. }*/
  60.  
  61.  
  62. //cf. https://gist.github.com/james2doyle/5694700
  63. // requestAnimationFrame for Smart Animating https://goo.gl/sx5sts
  64. var requestAnimFrame = function () {
  65. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
  66. window.setTimeout(callback, 1000 / 60);
  67. };
  68. }();
  69.  
  70. function scrollTo(to, callback, duration = 1500) {//FIXME this always starts from '0', instead of the clicked element offsetTop -> This is because the position is calculated for the main <html> element, not the <iframe>'s <html> tag
  71. /*console.log('from:', from); //DEBUG
  72. // console.log('from.clientY:', from.clientY); //DEBUG
  73. // console.log('from.target.offsetTop:', from.target.offsetTop); //DEBUG
  74. // console.log('position():', document.documentElement.offsetTop || document.body.parentNode.offsetTop || document.body.offsetTop); //DEBUG
  75. // console.log('document.documentElement:', document.documentElement); //DEBUG
  76. // console.log('document.body:', document.body); //DEBUG
  77. let start;
  78. if (isMouseEvent(from)) { //FIXME : the scroll starts at the link, not where the screen really is : fix that
  79. // start = from.target.offsetTop;
  80. start = from.pageY; //FIXME
  81. }
  82. else {
  83. start = from;
  84. }*/
  85.  
  86. if (isDomElement(to)) {
  87. // console.log('this is an element:', to); //DEBUG
  88. to = to.offsetTop;
  89. }
  90. /*else {
  91. // console.log('this is NOT an element:', to); //DEBUG
  92. }*/
  93.  
  94. // because it's so fucking difficult to detect the scrolling element, just move them all
  95. function move(amount) {
  96. // document.scrollingElement.scrollTop = amount; //FIXME Test that
  97. document.documentElement.scrollTop = amount;
  98. document.body.parentNode.scrollTop = amount;
  99. document.body.scrollTop = amount;
  100. }
  101.  
  102. function position() {
  103. return document.documentElement.offsetTop || document.body.parentNode.offsetTop || document.body.offsetTop;
  104. }
  105.  
  106. var start = position(),
  107. change = to - start,
  108. currentTime = 0,
  109. increment = 20;
  110. console.log('start:', start); //DEBUG
  111. console.log('to:', to); //DEBUG
  112. console.log('change:', change); //DEBUG
  113.  
  114. var animateScroll = function () {
  115. // increment the time
  116. currentTime += increment;
  117. // find the value with the quadratic in-out easing function
  118. var val = Math.easeInOutQuad(currentTime, start, change, duration);
  119. // move the document.body
  120. move(val);
  121. // do the animation unless its over
  122. if (currentTime < duration) {
  123. requestAnimFrame(animateScroll);
  124. } else
  125. {
  126. if (callback && typeof callback === 'function') {
  127. // the animation is done so lets callback
  128. callback();
  129. }
  130. }
  131. };
  132.  
  133. animateScroll();
  134. }
  135.  
  136. init();
  137. })();
  138.  
  139. //-------------------- Unimportant js functions --------------------
  140. // easing functions https://goo.gl/5HLl8
  141. //t = current time
  142. //b = start value
  143. //c = change in value
  144. //d = duration
  145. Math.easeInOutQuad = function (t, b, c, d) {
  146. t /= d / 2;
  147. if (t < 1) {
  148. return c / 2 * t * t + b;
  149. }
  150. t--;
  151. return -c / 2 * (t * (t - 2) - 1) + b;
  152. };
  153.  
  154. Math.easeInCubic = function (t, b, c, d) {
  155. var tc = (t /= d) * t * t;
  156. return b + c * tc;
  157. };
  158.  
  159. Math.inOutQuintic = function (t, b, c, d) {
  160. var ts = (t /= d) * t,
  161. tc = ts * t;
  162. return b + c * (6 * tc * ts + -15 * ts * ts + 10 * tc);
  163. };
  164.  
  165. function isDomElement(obj) {
  166. return obj instanceof Element;
  167. }
  168.  
  169. function isMouseEvent(obj) {
  170. return obj instanceof MouseEvent;
  171. }
  172.  
  173. function findScrollingElement(element) {//FIXME Test this too
  174. do {
  175. if (element.clientHeight < element.scrollHeight || element.clientWidth < element.scrollWidth) {
  176. return element;
  177. }
  178. } while (element = element.parentNode);
  179. }

That’s all! hopefully, you have successfully integrated this smooth scroll to anchor code snippet into your project. If you have any questions or are facing any issues, please feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X