Apu
June 03, 2023 ›
#animation
›
#HowTo
❌
Scroll to top in JavaScript with animation
In this article, you will learn how to create a "scroll to top" button with animation using pure Javascript without Jquery.
We will use the scrollTop() method to go to a specified location of the current page.
scrollTop() method takes two parameters scrollTop(x,y).
The x-axis is a horizontal line and the y-axis is a vertical line.
If we pass both parameters as 0, the page will reach to the left and top of the page.
- In the above example, I have created a <button> element and set its position to fixed. So that when we scroll the page, the button stays in one place. Even, the myFunction() is executed when the button is clicked.
- Inside the myFunction(), we have called the scrollTop() method and passed both parameters as 0.
function myFunction() { window.scrollTo(0, 0); } - To scroll slowly, we add the scroll-behavior css property with its value smooth to the html element.
html{ scroll-behavior:smooth; }
In the above example, we have explained how to create scroll to top button using javascript with animation. Click on the button to open the code in editor.
Demo : scroll to top with animation
<html>
<style>
html{
scroll-behavior:smooth;
}
.my-btn{
pa-dding:6px 12px;
background:#0000ff;
color:#fff;
border-radius:6px;
position: fixed;
bottom: 10px;
right:10px;
}
</style>
<body style="height:1500px;background:#eee">
<h1>The example of scrollTop() method.</h1>
<button class="my-btn" onclick="myFunction()">Top</button>
<script>
function myFunction() {
window.scrollTo(0, 0);
}
</script>
</body>
</html>
Try it Yourself »
save
listen
AI Answer
Scroll to top in JavaScript with animation
0
In this article, you will learn how to create a "scroll to top" button with ani…
asked
Apu
0 answers
2915
In this article, you will learn how to create a "scroll to top" button with ani…
Answer Link
answered
Apu
