Skip to content

Instantly share code, notes, and snippets.

@pwelter34
Created August 27, 2025 15:09
Show Gist options
  • Select an option

  • Save pwelter34/e0475eda346ff5c0cb6735080c014b85 to your computer and use it in GitHub Desktop.

Select an option

Save pwelter34/e0475eda346ff5c0cb6735080c014b85 to your computer and use it in GitHub Desktop.
Smooth scrolling for hash links in Blazor
// 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