scroll to top javascript
- Published
- Reading time
- 2 min read
- Length
- 341 words
On this page
Scroll to Top JavaScript#
Have you ever found yourself scrolling through a long web page only to realize that you need to go back to the top? Scrolling all the way up can be tiresome and time-consuming. Luckily, there is a quick and easy solution to this problem - adding a "scroll to top" button on your website.
How to Create a Scroll to Top Button#
To create a scroll to top button, you'll need to use JavaScript. Here's a simple script you can use:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}The script above creates a button that appears when the user has scrolled down 20 pixels or more from the top of the page. When the button is clicked, it brings the user back to the top of the page.
How to Add the Button to Your Website#
To add the button to your website, you'll need to add the following HTML code:
TopThis creates a button with an ID of "myBtn" that triggers the "topFunction" when clicked.
Other Ways to Create a Scroll to Top Button#
There are other ways to create a scroll to top button, including using jQuery or CSS. Here's an example using CSS:
Back to top
.scroll-to-top {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
}
.scroll-to-top:hover {
color: #fff;
}
.scroll-to-top:focus {
outline: none;
}
.scroll-to-top:after {
content: "\2191";
}
.scroll-to-top:focus:after,
.scroll-to-top:hover:after {
content: "";
}The CSS above creates a link that appears at the bottom right of the page. When clicked, it brings the user back to the top of the page. The arrow symbol is added using the ":after" pseudo-class.
Overall, adding a scroll to top button can greatly improve the user experience on your website. Whether you choose to use JavaScript, jQuery, or CSS, the end result is the same - a quick and easy way for users to navigate your website.