How to Create Scroll to top button in 2021 | Back to top button Using HTML CSS & JavaScript
Learn How to add a functional Back to Top Button in the website using HTML, CSS, and JavaScript
Download Code Files
How to Create Scroll to top button in 2021 | Back to top button Using Only HTML CSS & JavaScript
Learn How to add a functional Back to Top Button in the website using HTML, CSS, and JavaScript | Back To Top (Scroll To Top) Button Using HTML5, CSS3, and JavaScript. Smooth scrolling effect is also added, at first with a CSS-only solution, and then with JavaScript, in order to achieve cross-browser compatibility.
Let Start Coding
HTML
<!DOCTYPE html>
<html>
<head>
<title>Scroll Top Button</title>
</head>
<body>
<img src="https://previews.123rf.com/images/khz/khz0801/khz080100099/2460442-old-scroll-background-for-your-messages-and-designs-with-ornaments.jpg" style="width: 100%">
<a href="#" id="Button">
<img src="https://pbs.twimg.com/profile_images/378800000109924862/605a6c7756beee14fb29dfc75432d2e5_400x400.png" id="button" style="width: 100px">
</a>
</body>
</html>
Let Style a Button
body , html{
scroll-behavior: smooth;
}
#Button{
position: absolute;
top: 76%;
left: 82%;
position: fixed;
width: 100px;
display: none;
}
Let's write Functionality using JavaScript
<script type="text/javascript">
var mybutton = document.getElementById("Button");
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
</script>