Single-page JavaScript page navigation
Last updated: June 4, 2025
Introduction
…
With buttons
See the Pen HTML cheatsheet 1 / display types by perpetual.education (@perpetual-education) on CodePen.
With buttons and popstate for history
See the Pen HTML cheatsheet 1 / display types by perpetual.education (@perpetual-education) on CodePen.
With links and hashchange
See the Pen HTML cheatsheet 1 / display types by perpetual.education (@perpetual-education) on CodePen.
Accessibility and usability concerns for single-page navigation
- Screen reader support:
Usearia-live="polite"
to announce content updates dynamically. - Focus management:
Shift focus to key elements like headings when content changes.
Usetabindex="-1"
on non-interactive elements to make them focusable. (but be careful how that could affect people) - Scroll position:
Reset the scroll to the top usingwindow.scrollTo(0, 0)
after view changes. - Back/forward button behavior:
Implement listeners forpopstate
orhashchange
to handle navigation properly. - Page titles:
Dynamically updatedocument.title
to match the new content for accessibility and SEO. - JavaScript dependency:
Provide fallback functionality so the site remains usable if JavaScript fails. - URL bookmarking/sharing:
Ensure URLs reflect the correct state so users can bookmark or share them without issues. - Navigation structure:
Test with keyboard-only users to ensure proper focus management and smooth tab navigation.
Key difference between hash and history API navigation
- Hash navigation:
Easier to implement but results in URLs with hashes (e.g.,#about
). - History API navigation:
Produces cleaner URLs (e.g.,/about
) but requires more effort to manage
popstate
events and accessibility concerns.