Reputation:
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?
Upvotes: 2
Views: 4477
Reputation: 1078
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.
Upvotes: 6
Reputation: 621
Definition and Usage (of document.document.Element)
The documentElement property returns the documentElement of a document, as an Element object.
For HTML documents the returned object is the HTML element.
Note: If the HTML element is missing, the return value is null.
http://www.w3schools.com/jsref/prop_document_documentelement.asp
you shoud scroll not the html element but instead the body... as vikton was giving an example.
Upvotes: 0