What element should I use for JavaScript actions?
Actions that does something like play/pause/stop/new/open/save/print/close, etc.
<a id="play" href="#">Play</a>
<a href="#play">Play</a>
<button id="play" tabindex="0">Play</button>
<div id="play" role="button" tabindex="0">Play</div>
I see many people use anchors <a>
with a href="#"
but that doesn't feel very semantic, it feels like anchors are for hyperlinks that point to a resource, not for actions that does stuff. Then you have to hack it around with event.preventDefault
(i.e. return false
).
I rarely see people use the <button>
element, but isn't it what is supposed to be used?
The best way to decide which element has the best semantics for a JS based user interaction is to ask what you want to happen if the JS fails (which it will.
Think progressive enhancement. Think unobtrusive JavaScript.
Should the user just go to another page? Use a link. The href
will be the fallback from when the JS fails.
Should the user go to another page while sending some data or making a POST request? Use a button, put it in a form.
Is it impossible to have any kind of server fallback? Use a <button type="button">
and consider generating it from JS/DOM instead of HTML.