CSS के साथ "स्क्रॉल बैक टू टॉप" बटन बनाने के लिए निम्नलिखित कोड है -
उदाहरण
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: Arial, Helvetica, sans-serif; font-size: 20px; height: 120vh; /*To produce a scrollbar*/ } div p { font-size: 32px; } .topBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 1; font-size: 24px; border: none; outline: none; background-color: rgb(90, 23, 129); color: white; cursor: pointer; padding: 15px; border-radius: 4px; } .topBtn:hover { background-color: rgb(75, 15, 145); } </style> </head> <body> <button class="topBtn">Top</button> <h1>Scroll to top button example</h1> <div> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Beatae sit, voluptatem minima quibusdam facere hic eum excepturi ex eius, accusamus cum. Iusto quibusdam quo alias laboriosam, debitis natus vero. Accusantium iusto rerum quisquam enim porro! Animi reiciendis quidem esse veritatis quis excepturi mollitia alias, odio error at temporibus deleniti placeat dignissimos id? Suscipit autem incidunt ad sit soluta natus beatae eveniet eaque id. Atque vitae debitis neque assumenda incidunt iste ut consequuntur cupiditate inventore, eveniet quo adipisci natus blanditiis illum facilis, eius harum cumque enim pariatur magnam sapiente perspiciatis numquam! Sapiente, molestias quaerat. Numquam laborum explicabo quam sapiente dicta aliquam.</p> </div> <script> var topButton = document.querySelector(".topBtn"); topButton.addEventListener("click", topScroll); window.onscroll = function() { scrollBtnShow(); }; function scrollBtnShow() { if ( document.body.scrollTop > 20 || document.documentElement.scrollTop > 20 ) { topButton.style.display = "block"; } else { topButton.style.display = "none"; } } function topScroll() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } </script> </body> </html>
आउटपुट
यह निम्नलिखित आउटपुट उत्पन्न करेगा-
नीचे स्क्रॉल करने पर स्क्रॉल टॉप बटन इस प्रकार दिखाई देगा -