Widget:ScrollToTopSidebar: Difference between revisions

From Bodhicitta
((by SublimeText.Mediawiker))
((by SublimeText.Mediawiker))
Line 2: Line 2:
// Create the scroll to top button
// Create the scroll to top button
const scrollToTopButtonSb = document.createElement('button');
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.innerHTML = 'Top <i class="fa-sharp-duotone fa-solid fa-up-to-bracket"></i>';
scrollToTopButtonSb.setAttribute('id', 'scrollToTop');
scrollToTopButtonSb.setAttribute('id', 'scrollToTop');


Line 8: Line 8:
const container = document.getElementById('scrollToTopContainer');
const container = document.getElementById('scrollToTopContainer');
container.appendChild(scrollToTopButtonSb);
container.appendChild(scrollToTopButtonSb);
// Handle initial hash navigation
window.addEventListener('load', () => {
if (window.location.hash) {
setTimeout(() => {
const element = document.querySelector(window.location.hash);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}, 100);
}
});


// Show/hide the button based on scroll position
// Show/hide the button based on scroll position

Revision as of 12:42, 4 April 2025

<script> // Create the scroll to top button const scrollToTopButtonSb = document.createElement('button'); scrollToTopButtonSb.innerHTML = 'Top '; scrollToTopButtonSb.setAttribute('id', 'scrollToTop');

// Add the button to the document body const container = document.getElementById('scrollToTopContainer'); container.appendChild(scrollToTopButtonSb);

// Handle initial hash navigation window.addEventListener('load', () => { if (window.location.hash) { setTimeout(() => { const element = document.querySelector(window.location.hash); if (element) { element.scrollIntoView({ behavior: 'smooth' }); } }, 100); } });

// 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>