How to create a Scroll To Top Button
HTML CSS JavaScript

How to create a Scroll To Top Button

Mishel Shaji
Mishel Shaji

A scroll to top button allows users to easily scroll back to top of the web page when clicked on the button. Adding a scroll to top button to your website can be a great way to allow your users to navigate, especially if you have long-scrolling pages.

Example – Creating a simple scroll to top button

The HTML markup

<h1>Scroll down</h1>
<p style="margin-bottom:2000px;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat, maxime nesciunt autem temporibus eum quos natus, quasi minus optio et ut officia voluptates eos tempora beatae commodi eveniet debitis dolorum.</p>
<button onclick="scrollToTop()" id="scroll-btn" title="Go to top">Top</button>

CSS Styles

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

JavaScript code

<script>
// When the user scrolls down 20px from the top of the document,we will show the button
window.onscroll = function()
{
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20)
    {
    	document.getElementById("scroll-btn").style.display = "block";
    }
    else
    {
    	document.getElementById("scroll-btn").style.display = "none";
    }
};

function scrollToTop()
{
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox and Opera
}
</script>

Complete code

<!DOCTYPE html>
<html>
<head>
<title>HTML Scroll To Top</title>
<meta name="robots" content="noindex">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
#scroll-btn{
background-color: teal;
border: medium none;
border-radius: 8px;
bottom: 20px;
color: white;
cursor: pointer;
display: none;
outline: medium none;
padding: 10px 15px 7px;
position: fixed;
right: 30px;
z-index: 99;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Scroll down</h1>
<p style="margin-bottom:2000px;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat, maxime nesciunt autem temporibus eum quos natus, quasi minus optio et ut officia voluptates eos tempora beatae commodi eveniet debitis dolorum.</p>
<button onclick="scrollToTop()" id="scroll-btn" title="Go to top"><i class="fa fa-arrow-circle-o-up" aria-hidden="true"></i></button>
<script>
// When the user scrolls down 20px from the top of the document,we will show the button
window.onscroll = function()
{
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20)
{
document.getElementById("scroll-btn").style.display = "block";
}
else
{
document.getElementById("scroll-btn").style.display = "none";
}
};

function scrollToTop()
{
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
</script>
</body>
</html>