Back to top button without jQuery
javascript, jquery
Solution
Will make the scroll to top without animation in vanilla JS
document.getElementById('backtotop_js').onclick = function () {
document.documentElement.scrollTop = 0;
}
EDIT: changed document.getElementsByTagName('body')[0] to document.documentElement as per Rudie's comment below.
Problem
I want to create a button "Back to top" with javascript. My code (which I found on StackOverflow) does not work when I click the button nothing happens. HTML ``` <button type="button" id="backtotop_js">To the top</button> ``` JAVASCRIPT ``` document.getElementById('backtotop_js').onclick = function () { scrollTo(document.documentElement, 0, 1250); }; function scrollTo(element, to, duration) { var start = element.scrollTop, change = to - start, currentTime = 0, increment = 20; var animateScroll = function(){ currentTime += increment; var val = Math.easeInOutQuad(currentTime, start, change, duration); element.scrollTop = val; if(currentTime < duration) { setTimeout(animateScroll, increment); } }; animateScroll(); } Math.easeInOutQuad = function (t, b, c, d) { t /= d/2; if(t < 1) return c/2*t*t + b; t--; return -c/2 * (t*(t-2) - 1) + b; }; ``` (I'm using Chrome and Firefox) Where's the mistake?