Created
August 27, 2025 15:09
-
-
Save pwelter34/e0475eda346ff5c0cb6735080c014b85 to your computer and use it in GitHub Desktop.
Smooth scrolling for hash links in Blazor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Smooth scrolling for hash links | |
| function hashLinkScrolling() { | |
| // Get all links that start with # | |
| const hashLinks = document.querySelectorAll('a[href^="#"]'); | |
| hashLinks.forEach(link => { | |
| link.addEventListener('click', function(e) { | |
| // Prevent default anchor behavior | |
| e.preventDefault(); | |
| // Get the href value (the hash) | |
| const targetId = this.getAttribute('href'); | |
| // Skip empty hashes or just "#" | |
| if (!targetId || targetId === '#') { | |
| return; | |
| } | |
| // Find the target element | |
| const targetElement = document.querySelector(targetId); | |
| if (!targetElement) { | |
| return; | |
| } | |
| // Smooth scroll to the target element | |
| targetElement.scrollIntoView({ | |
| behavior: 'smooth', | |
| block: 'start' | |
| }); | |
| }); | |
| }); | |
| } | |
| // Update on page load | |
| if (document.readyState === 'loading') { | |
| document.addEventListener('DOMContentLoaded', hashLinkScrolling); | |
| } else { | |
| hashLinkScrolling(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment