HTMHell supports Black Lives Matter. ✊🏾 Code is always political.

#8 anchor tag used as button

submitted on by Sven

Bad code Bad code

<a href="#" onclick="modal.open()">Login</a>

Issues and how to fix them Issues and how to fix them

  1. If the a element has an href attribute, it represents a link to another resource like a page or a PDF document.
  2. The purpose of the element in this example is to trigger an action on the same page with JavaScript. The button element with the type button is more suitable because it has no default behaviour and it’s designed to trigger actions on user input.
  3. Browsers and devices that do not support JavaScript will not be able to access the content in the modal.

Good code Good code

Solution #1: Use a button element Solution #1: Use a button element

<button type="button" onclick="modal.open()">Login</button>

Since the only purpose of this element is to trigger an action on the same page instead of navigation; the <button></button> element is the semantically correct element to use.

Solution #2: Add a valid href value to the login form Solution #2: Add a valid href value to the login form

<a href="/login" onclick="modal.open()">Login</a>

Another solution is to add a href value to a location where the same actions as the modal can be performed.
This provides a fallback for browsers and devices that do not support JavaScript. This is an example of progressive enhancement.