I have a webapplication where (as in many other ones out there) you click on an image to do something, for instance, mark an entry, send a mail, flag something…
Short, clicking on the image is supposed to call an action (via javascript, but that’s not the point).
I was wondering, what is the “right” way to do this?
<a>-tag? Hmm… actually it is not a link…<button>? Because obviously a button is the semantic element for calling an action…<div>?
Any hints?
Short Answer
Use an
<img>– not a button or an anchor or an input – as the rest suggest that the element is interactive, even without JavaScript.Long Answer
I disagree; that is the point 🙂
Because the clicking activates JS-only features, your image should only be available in a JS environment.
As such the proper way is to insert it with JavaScript; while an HTML document should be semantically correct, a DOM structure doesn’t really need to be semantically correct, so which element you use becomes irrelevant.
The Wrong Way
These are all wrong because a user who doesn’t have JavaScript sees these items and can’t use them.
Of all of these, I’d say the
<img>is the lesser evil, as it doesn’t suggest an interactive element. The greatest evil is using the<a>as an anchor should be a hyperlink to another document, and you should never, ever use thejavascript:protocol.You’ll still have the same problem when you add the JavaScript event handlers externally:
As, again, you still have the (non-functioning) hyperlink available to those users who don’t have JavaScript.
Instead
Instead, insert the whole damn thing using DOM scripting! I’m going to use an
<img>with anonclickevent: