How can I stop a link from navigating while handling its click?
Quick answer
Call event.preventDefault() inside the link’s click handler when your code is taking over an action the link would normally perform, such as showing an app view instead of navigating to a new page. For ordinary links that should open their destination, do not cancel the default action. Google’s example uses this approach for single-page-app routing and updates browser history with pushState; it does not cover every event-handling edge case. [S1]
The question, the details, the next step.
A practical checklist
Decide whether the link represents an app-handled action or ordinary navigation.
Attach the click handler to the intended link.
Call
event.preventDefault()only when your code takes over the link’s action.Provide the replacement action, such as showing the intended app view.
Test an app-handled link and an ordinary link separately.
A few more useful answers
Does `preventDefault()` itself load the new view?
No. In the example, it cancels the link’s default navigation; your application must supply the view-changing action.
Should I cancel navigation on every link in a single-page app?
Do so only for links your app is handling. Preserve normal navigation for links that should follow their destination. [S1]
Does the example cover every browser event edge case?
No. The cited guidance demonstrates a single-page-app routing pattern, but it does not explain all event-handling edge cases. [S1]
Sources
References used for this guide.
- [S1] Understand the JavaScript SEO basics — Google Search Central developers.google.com · Checked
