JAVASCRIPT
Create a 'Scroll to Top' Button
Implement a convenient 'Scroll to Top' button that appears on scroll and smoothly navigates users back to the page's beginning using JavaScript DOM and `window.scrollTo`.
// HTML for the button (e.g., at the end of body):
// <button id="scrollTopBtn" style="display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: #555; color: white; cursor: pointer; padding: 15px; border-radius: 4px;">Top</button>
const scrollTopBtn = document.getElementById('scrollTopBtn');
const scrollThreshold = 300; // Pixels from top before button appears
// Show/hide the button based on scroll position
window.addEventListener('scroll', () => {
if (document.body.scrollTop > scrollThreshold || document.documentElement.scrollTop > scrollThreshold) {
scrollTopBtn.style.display = 'block';
} else {
scrollTopBtn.style.display = 'none';
}
});
// When the user clicks on the button, scroll to the top of the document
scrollTopBtn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth' // For smooth scrolling
});
});
How it works: This snippet creates a 'Scroll to Top' button that dynamically appears or disappears based on the user's scroll position. An event listener on the `window` checks `document.body.scrollTop` or `document.documentElement.scrollTop` to determine if the user has scrolled past a predefined `scrollThreshold`. If so, the button's `display` style is set to 'block'; otherwise, it's set to 'none'. When clicked, the button uses `window.scrollTo` with `behavior: 'smooth'` to provide a pleasant animated scroll back to the top of the page.