Widget:ScrollToTop: Difference between revisions
((by SublimeText.Mediawiker)) |
((by SublimeText.Mediawiker)) |
||
(25 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
<button id | <script> | ||
// Create the scroll to top button | |||
const scrollToTopButton = document.createElement('button'); | |||
scrollToTopButton.innerHTML = '↑'; // Up arrow character | |||
scrollToTopButton.setAttribute('id', 'scrollToTop'); | |||
scrollToTopButton.style.cssText = ` | |||
position: fixed; | |||
right: 20px; | |||
bottom: 20px; | |||
width: 50px; | |||
height: 50px; | |||
border-radius: 50%; | |||
background-color: rgb(28 64 90); | |||
color: #fff; | |||
font-size: 24px; | |||
border: none; | |||
cursor: pointer; | |||
display: none; | |||
z-index: 1000; | |||
`; | |||
// Add the button to the document body | |||
document.body.appendChild(scrollToTopButton); | |||
// Show/hide the button based on scroll position | |||
window.addEventListener('scroll', () => { | |||
if (window.pageYOffset > 300) { | |||
scrollToTopButton.style.display = 'block'; | |||
} else { | |||
scrollToTopButton.style.display = 'none'; | |||
} | |||
}); | |||
// Scroll to top when the button is clicked | |||
scrollToTopButton.addEventListener('click', () => { | |||
window.scrollTo({ | |||
top: 0, | |||
behavior: 'smooth' | |||
}); | |||
}); | |||
</script> |
Latest revision as of 13:38, 13 December 2024
<script> // Create the scroll to top button const scrollToTopButton = document.createElement('button'); scrollToTopButton.innerHTML = '↑'; // Up arrow character scrollToTopButton.setAttribute('id', 'scrollToTop'); scrollToTopButton.style.cssText = ` position: fixed; right: 20px; bottom: 20px; width: 50px; height: 50px; border-radius: 50%; background-color: rgb(28 64 90); color: #fff; font-size: 24px; border: none; cursor: pointer; display: none; z-index: 1000; `;
// Add the button to the document body document.body.appendChild(scrollToTopButton);
// Show/hide the button based on scroll position window.addEventListener('scroll', () => { if (window.pageYOffset > 300) { scrollToTopButton.style.display = 'block'; } else { scrollToTopButton.style.display = 'none'; } });
// Scroll to top when the button is clicked scrollToTopButton.addEventListener('click', () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }); </script>