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
462
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!
 
Recommended Threads
Replies
16
Views
9,746
Replies
94
Views
45,648
Replies
11
Views
5,141
Replies
0
Views
3,192
Replies
5
Views
5,128

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