Welcome to Peter Lightspeed Blog

Header Ads Widget

Responsive Advertisement

How to Add an Animated Scroll-to-Top Button Using HTML, CSS & JS

 HTML:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Back to Top button</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css"> </head> <body> <div></div> <button id="scrollTopBtn"><i class="bi bi-arrow-up-circle-fill"></i></button> </body> </html>

CSS:

#scrollTopBtn { position: fixed; bottom: 30px; right: 30px; background-color: #ff4747; color: white; border: none; padding: 10px 15px; border-radius: 50%; cursor: pointer; font-size: 20px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); display: none; transition: all 0.3s ease-in-out; } #scrollTopBtn:hover { background-color: #ff2929; transform: translateY(-5px); }

JavaScript:

const scrollBtn = document.getElementById("scrollTopBtn"); window.onscroll = function() { if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) { scrollBtn.style.display = "block"; } else { scrollBtn.style.display = "none"; } }; scrollBtn.onclick = function() { window.scrollTo({ top: 0, behavior: "smooth" }); };


Post a Comment

0 Comments