- 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:
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!
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>
Hope it helps!