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
If you do want smooth scrolling, try something like this:
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
That will take any <a>
tag whose href="#top"
and make it smooth scroll to the top.
The old #top
can do the trick
document.location.href = "#top";
Works fine in FF, IE and Chrome
This simple solution works natively and implements a smooth scroll to any position.
It avoids using anchor links (those with #
) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).
Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.
<body>
<section id="top">
<!-- your content -->
</section>
<div id="another"><!-- more content --></div>
Then as a button you can use a link, just edit the onclick attribute with a code like this.
<a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
Where the argument of document.getElementById
is the id of the tag you want to scroll to after click.
<script>
$(function(){
var scroll_pos=(0);
$('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>
Edit:
$('html, body').animate({scrollTop:(scroll_pos)}, 2000);
Another way scroll with top and left margin:
window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });
If you want to do smooth scrolling, please try this:
$("a").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
Another solution is JavaScript window.scrollTo method :
window.scrollTo(x-value, y-value);
Parameters :
$(".scrolltop").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
.section{
height:400px;
}
.section1{
background-color: #333;
}
.section2{
background-color: red;
}
.section3{
background-color: yellow;
}
.section4{
background-color: green;
}
.scrolltop{
position:fixed;
right:10px;
bottom:10px;
color:#fff;
}
<html>
<head>
<title>Scroll top demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div class="content-wrapper">
<div class="section section1"></div>
<div class="section section2"></div>
<div class="section section3"></div>
<div class="section section4"></div>
<a class="scrolltop">Scroll top</a>
</div>
</body>
</html>