Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth scroll anchor links WITHOUT jQuery

Is it possible to use smooth scroll to anchor links but without jQuery? I am creating a new site and I don't want to use jQuery.

like image 467
drozdzynski Avatar asked Jul 18 '13 20:07

drozdzynski


1 Answers

Extending this answer: https://stackoverflow.com/a/8918062/3851798

After defining your function of scrollTo, you can pass the element you want to scrollTo in the function.

function scrollTo(element, to, duration) {     if (duration <= 0) return;     var difference = to - element.scrollTop;     var perTick = difference / duration * 10;      setTimeout(function() {         element.scrollTop = element.scrollTop + perTick;         if (element.scrollTop === to) return;         scrollTo(element, to, duration - 10);     }, 10); } 

If you have a div with an id="footer"

<div id="footer" class="categories">…</div> 

In the script that you run to scroll you can run this,

elmnt = document.getElementById("footer"); scrollTo(document.body, elmnt.offsetTop, 600); 

And there you have it. Smooth scrolling without jQuery. You can actually play around with that code on your browser's console and fine tune it to your liking.

like image 65
Tejas Anil Shah Avatar answered Sep 18 '22 21:09

Tejas Anil Shah