Hash Changes and Fragment Navigation
You'll learn how to use URL fragments (the part after #) to navigate within a page and respond to changes dynamically.
What Are URL Fragments?
The hash is the part of a URL that comes after the # symbol, like https://example.com/page#section2. It's called a "fragment" because it traditionally points to a specific fragment (or section) of the page. When you click a link with a hash, the browser scrolls to an element with that matching id.
Think of URL fragments like bookmarks in a physical book—they let you jump directly to a specific section without changing the overall document (or page) you're reading.
Using Hash for In-Page Navigation
When you set location.hash or create links with hash values, the browser automatically scrolls to matching elements:
// Navigate to a section
location.hash = '#contact'; // Scrolls to <div id="contact">
// Read current hash
console.log(location.hash); // "#contact"
The hashchange Event
The hashchange event fires whenever the fragment changes—whether from user navigation, back/forward buttons, or JavaScript:
window.addEventListener('hashchange', () => {
console.log('Hash changed to:', location.hash);
// Example: Show different content based on hash
if (location.hash === '#about') {
// Display about section
} else if (location.hash === '#services') {
// Display services section
}
});
This pattern is perfect for single-page applications where you want different "views" without full page reloads.
Practical Uses
Hash navigation is commonly used for tabs, accordions, and section navigation that should be bookmarkable and work with browser back/forward buttons.
Key Takeaway: URL fragments provide in-page navigation with location.hash, and the hashchange event lets you respond dynamically to fragment changes for interactive, bookmarkable experiences.