How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I\'m not looking to achieve smooth scroll
You could simply use a target from your link, such as #someid, where #someid is the div's id.
Or, you could use any number of scrolling plugins that make this more elegant.
http://plugins.jquery.com/project/ScrollTo is an example.
You dont need JQuery. Simply you can call the script
window.location = '#'
on click of the "Go to top" button
Sample demo:
output.jsbin.com/fakumo#
PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.
smooth scroll, pure javascript:
(function smoothscroll(){
var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo (0,currentScroll - (currentScroll/5));
}
})();
This will work:
window.scrollTo(0, 0);
If you don't want smooth scrolling, you can cheat and stop the smooth scrolling animation pretty much as soon as you start it... like so:
$(document).ready(function() {
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "1");
$('html, body').stop(true, true);
//Anything else you want to do in the same action goes here
return false;
});
});
I've no idea whether it's recommended/allowed, but it works :)
When would you use this? I'm not sure, but perhaps when you want to use one click to animate one thing with Jquery, but do another without animation? ie open a slide-in admin login panel at the top of the page, and instantly jump to the top to see it.
Pure JavaScript solution:
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
I write an animated solution on Codepen
Also, you can try another solution with CSS scroll-behavior: smooth property.
html {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}