href="javascript:void(0)" is an older HTML/JavaScript trick used on <a> tags to prevent the browser from navigating to a new URL or jumping to the top of the page when clicked. The javascript: pseudo-protocol evaluates void(0), which evaluates 0 and returns undefined—so the browser has no navigation target or replacement document content to load.
1. How javascript:void(0) Works Under the Hood
When a user clicks <a href="javascript:void(0)">, two things happen:
-
javascript:scheme: Tells the browser to execute the expression after the colon instead of requesting a web address. -
void(0)expression: Evaluates0and always returnsundefined. Withoutvoid(...), an expression that evaluates to a value (likejavascript:0) can cause some browsers to replace the current page content with that evaluated return value.<!-- Legacy pattern: click handled by JS without jumping to “#” --> <a id=“open-modal-btn” href=“javascript:void(0)”>Open Settings</a>
<script> document.querySelector(“#open-modal-btn”)?.addEventListener(“click”, (event) => { event.preventDefault(); console.log(“Opening settings modal…”); }); </script>
2. Why Developers Used It—and Better Modern Alternatives
Historically, developers used javascript:void(0) instead of href="#" because href="#" scrolls the page back to the top and appends to the URL hash if preventDefault() is forgotten. Today, better semantic patterns exist:
-
Use
<button type="button">for actions: If clicking triggers a modal, toggle, or JS action rather than navigating to a URL, a<button type="button">is more accessible, works with keyboard activation (EnterandSpace), and avoids fake-link semantics. -
Use a real URL or
event.preventDefault()on<a>: If the element genuinely links somewhere (or has a fallback destination), givehrefa real path and callevent.preventDefault()when handling it client-side.<!-- Preferred modern pattern for non-navigation actions --> <button id=“open-modal-btn” type=“button”>Open Settings</button>
3. Common Traps and Security Caveats
- Accessibility and screen readers: An
<a>withjavascript:void(0)announces itself as a link even when it behaves like an action button, which can confuse assistive technologies. - Strict CSP (
Content-Security-Policy): Inlinejavascript:URLs can clash with restrictive security policies or codebases that ban inline script execution. - Middle-click / “Open in new tab”: Users expect links (
<a>) to open a destination in a new tab—javascript:void(0)provides no real URL target.
TL;DR: href="javascript:void(0)" runs a no-op expression that returns undefined so clicking an <a> tag does not navigate or jump to , though <button type="button"> is usually cleaner and more accessible for actions that do not navigate.
Are you refactoring legacy markup, wiring up a modal or UI action, or dealing with a link that needs both a fallback URL and JS behavior?
