This is a fairly simple accessibility question.
Say we have a toggle link/button which, when clicked, toggles the mobile menu. Which is the more accessible format for such a button?
We have 4 total options, separated by
button
tag vs.a
tag,
and
onclick
attribute vs.$("#showMenu").on("click", function() { showMenu() } )
All Options
<a href="#" onclick="showMenu();"></a>
<button onclick="showMenu();"></button>
<a href="#" id="showMenu"></a>
- with
$("#showMenu").on("click",function() { showMenu() } );
- with
<button id="showMenu"></button>
- with
$("#showMenu").on("click",function() { showMenu() } );
- with
Pros and Cons
I have read that, for best accessibility, the <button>
tag should be used for javascript actions, and <a>
tags for normal links. Unfortunately, I cannot find that article again.
Folks always say to "separate logic from content". My answer is: do you really think your Javascript showMenu()
function will work without that link to trigger it? So, are you really separating logic from content?
Along those lines, I do like the idea of using event handlers to attach events, however, this makes the code harder to maintain in certain circumstances, not easier. If I later delete that link or change the ID or class, I will lose the functionality. The onclick
attribute reminds me to tread carefully. If I have more than one link, or wish to be 508 compliant (see next paragraph), I will use an event handler.
The 508 standard demands that every onclick attribute be accompanied by an equivalent keyboard attribute. This drives me nuts, because keyboard users can trigger an onclick event through the key, and are used to doing so for text links.* In addition, if you DO add an onkeyup event handler of any sort, you need to filter for the key, etc. so that users don't get "stuck" on your link and become completely unable to browse throughout the rest of the site.
*See note: http://alistapart.com/article/popuplinks#section6
My questions
- Is a
<button>
tag better for accessibility? - Why or why not?
- Which of the 4 is the best for accessibility?
Please note that this question is similar to the following question, but I am much more interested in the <button>
vs. <a>
argument. Plus, the following question does not even mention accessibility, which is what I am primarily concerned with.
jQuery.click() vs onClick
A lot of this is a matter of opinion, but to me, a link takes you somewhere while a button performs an action. In your case, if it were me, I would use a button. And I would use the onclick with it, so as you mentioned, to not lose track of it later.
So your option #2.