Ralph David Abernathy Ralph David Abernathy - 1 year ago 65
HTML Question

Is it more accessible to use a <button> or <a> to open/close a modal?

From my understanding, buttons are used to carry out functions and links are used to navigate the user to a different page. But what is best practice in terms of opening and closing a modal?

<a id="testModal" href="#">Open Modal</a>


<button id="testModal">Open Modal</button>

Answer Source


Change the <a href="#"> to a <button> and put your event handler on it.

Some more context on which elements belongs where....

Does the Control Take Me to Another Page? Use an Anchor

If, when clicked, tapped, or activated by keyboard or voice (or insert novel interaction method here), the user is whisked to another URL (including an anchor on the same page), then use <a href="[URL]">. Make sure you use the href attribute and that it has a real URL, not a “#” (otherwise you’re probably relying on JavaScript, which is not at all necessary for a hyperlink). If an href points to just a “#”, then you’re probably doing it wrong. If it points to a named anchor as part of your progressive enhancement efforts, then that’s totally valid.

Does the Control Change Something on the Current Page? Use a Button

If, when activated, the user is not moved from the page (or to an anchor within the page), but instead is presented with a new view (message boxes, changes in layout, etc.), then use a <button>. While you could use an<input type="button">, it’s more likely you’ll get into conflicts with pre-existing styles and subsequent developers (like me).

Does the Control Submit Form Fields? Use a Submit

If, when activated, information the user has entered (either by manually typing or by choosing items on the screen) is being sent back to the server, then use an <input type="submit">. This has better live within a <form>. If you need more styling control or have to embed more than just a simple text string, use a <button type="submit"> instead.

Keyboard Considerations

Think of keyboard users for a moment. A hyperlink can be fired by pressing the enter key. But a true button can be fired by pressing the enter key or the space bar. When a hyperlink has focus and the user presses the space bar, the page will scroll one screenful. If there isn’t more to scroll then the user just experiences nothing. Given a set of interface elements that look the same, if some work with a space bar and some don’t, you can’t expect users to have much confidence in how the page behaves.

I think it’s also worth mentioning that events triggered by a space bar only fire when the key is released, whereas using the Enter key will fire the event as soon as you press the key down (prior to releasing it).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download