How to create a sticky button when scrolling browser using HTML, CSS, and JavaScript

Harry P

Well-known member
Registered
Joined
Feb 3, 2015
Messages
447
Points
28
Here is a complete file that demonstrates how to create a sticky button when scrolling the browser using HTML, CSS, and JavaScript:


Code:
<!DOCTYPE html>
<html>
  <head>
    <style>
      .sticky-button {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background-color: green;
        color: white;
        padding: 10px 20px;
        border-radius: 10px;
        cursor: pointer;
        transition: 0.3s ease;
      }

      .sticky-button.sticky {
        bottom: 20px;
        right: 20px;
      }
    </style>
  </head>
  <body>
    <button class="sticky-button">Sticky Button</button>

    <script>
      window.onscroll = function() {
        const button = document.querySelector(".sticky-button");
        if (window.pageYOffset >= 200) {
          button.classList.add("sticky");
        } else {
          button.classList.remove("sticky");
        }
      };
    </script>
  </body>
</html>
In this example, the .sticky-button class is initially positioned fixed with a bottom and right offset of 20px. When the user scrolls down 200px, the sticky class is added, which repositions the button to stay at the bottom right of the viewport.

Hope it helps!
 
Latest Threads
Replies
0
Views
45
Replies
2
Views
79
Replies
2
Views
78
Replies
2
Views
126

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top