Widget:ScrollToTopSidebar: Difference between revisions
((by SublimeText.Mediawiker)) |
((by SublimeText.Mediawiker)) |
||
| Line 1: | Line 1: | ||
<script> | <script> | ||
// Create the scroll to top button | // Create the scroll to top button | ||
const | const scrollToTopButtonSb = document.createElement('button'); | ||
scrollToTopButtonSb.innerHTML = 'Top <i class="fa-sharp-duotone fa-solid fa-up-to-bracket"></i>'; // Text and FA to top icon | |||
scrollToTopButtonSb.setAttribute('id', 'scrollToTop'); | |||
// Add the button to the document body | // Add the button to the document body | ||
const container = document.getElementById('scrollToTopContainer'); | const container = document.getElementById('scrollToTopContainer'); | ||
container.appendChild( | container.appendChild(scrollToTopButtonSb); | ||
// Show/hide the button based on scroll position | // Show/hide the button based on scroll position | ||
window.addEventListener('scroll', () => { | window.addEventListener('scroll', () => { | ||
if (window.pageYOffset > 300) { | if (window.pageYOffset > 300) { | ||
scrollToTopButtonSb.style.display = 'block'; | |||
} else { | } else { | ||
scrollToTopButtonSb.style.display = 'none'; | |||
} | } | ||
}); | }); | ||
// Scroll to top when the button is clicked | // Scroll to top when the button is clicked | ||
scrollToTopButtonSb.addEventListener('click', () => { | |||
window.scrollTo({ | window.scrollTo({ | ||
top: 0, | top: 0, | ||
Revision as of 17:29, 1 November 2024
<script> // Create the scroll to top button const scrollToTopButtonSb = document.createElement('button'); scrollToTopButtonSb.innerHTML = 'Top '; // Text and FA to top icon scrollToTopButtonSb.setAttribute('id', 'scrollToTop');
// Add the button to the document body const container = document.getElementById('scrollToTopContainer'); container.appendChild(scrollToTopButtonSb);
// Show/hide the button based on scroll position window.addEventListener('scroll', () => { if (window.pageYOffset > 300) { scrollToTopButtonSb.style.display = 'block'; } else { scrollToTopButtonSb.style.display = 'none'; } });
// Scroll to top when the button is clicked scrollToTopButtonSb.addEventListener('click', () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }); </script>