Should you use href or onclick for JavaScript callback handlers on HTML anchor links? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

Should you use href or onclick for JavaScript callback handlers on HTML anchor links?

message-square
0

Neither inline javascript: URLs in href nor inline onclick attributes are recommended for general JavaScript callback handlers on HTML anchor links (<a>). Instead, use a real destination URL (or # / valid route) in href and attach an addEventListener("click", handler) callback in JavaScript—calling event.preventDefault() inside the handler when the link runs a JS action instead of navigating—or use a native <button type="button"> when the control does not navigate to a URL at all.


1. Using href + addEventListener("click", ...) and event.preventDefault()

Keep behavior separated from markup by binding a JavaScript event listener (addEventListener or jQuery .on("click", ...)) and calling event.preventDefault() to stop default navigation:

// Attach a JavaScript callback cleanly to an anchor link without inline attributes
function bindActionLink(selector, onAction) {
  const linkEl = document.querySelector(selector);
  if (!(linkEl instanceof HTMLAnchorElement)) {
    return;
  }

  linkEl.addEventListener("click", (event) => {
    event.preventDefault();
    onAction(event, linkEl);
  });
}

bindActionLink("#export-report-link", (_event, el) => {
  const reportId = el.dataset.reportId;
  console.log("Running JS export callback for report:", reportId);
});
  • Clean separation of concerns: Keeps JavaScript logic out of HTML attributes, making code easier to test, maintain, and reuse across multiple links.
  • event.preventDefault(): Prevents the browser from following href or jumping the page scroll position when href="#" is used.
  • Works with data-* attributes: Store action metadata on data-* attributes and read el.dataset inside the callback.

2. When to Use <button type="button"> Instead of <a>

If clicking the control triggers a JavaScript action (opening a modal, toggling state, deleting a row, submitting an async action) and has no URL destination, a native <button type="button"> is semantically better and more accessible than an <a> tag:

// Prefer <button type="button"> for non-navigation JS actions
function wireActionButton(buttonId, callback) {
  const btn = document.getElementById(buttonId);
  if (!(btn instanceof HTMLButtonElement)) {
    return;
  }

  btn.addEventListener("click", (event) => {
    callback(event, btn);
  });
}

wireActionButton("open-modal-btn", () => {
  console.log("Opening modal via native button callback");
});
  • Semantic clarity & accessibility: Screen readers and keyboard users expect <button> for actions and <a> for navigation to a destination URL.
  • No accidental navigation or hash jumps: Buttons do not trigger browser navigation or URL hash changes if event.preventDefault() is forgotten.

3. Common Traps to Avoid

Using href="javascript:..." or inline onclick="..." on <a> tags introduces several pitfalls:

  • Using href="javascript:...": Acts like an eval()-style string, can conflict with strict Content Security Policy (unsafe-inline), breaks middle-click / “open in new tab” expectations, and can cause subtle page-state quirks.
  • Using inline onclick="..." strings: Mixes HTML and JS, makes passing dynamic references or debugging harder, and runs into CSP restrictions when inline scripts are disallowed.
  • Using href="#" without event.preventDefault(): Appends # to the URL and scrolls the viewport back to the top of the page on click.

TL;DR: Do not use href="javascript:..." or inline onclick attributes—use addEventListener("click", ...) with event.preventDefault() on <a> links (or use <button type="button"> for pure JS actions without navigation).

Are you handling a navigation link that also runs analytics/async work, intercepting a link for a SPA/modal action, or choosing between <a> and <button> for UI controls?