Wherever I have a Javascript action to trigger, I've always blindly put a <a href="#">
, and the onclick
listener on the anchor:
<ul>
<li><a href="#">Tab 1</a></li>
<li><a href="#">Tab 2</a></li>
<li><a href="#">Tab 3</a></li>
</ul>
<script>
$('li a').click(function(e) {
e.preventDefault();
// ...
});
</script>
However, I realize now that I was just doing it mechanically, and that this is much cleaner and simpler:
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<script>
$('li').click(function(e) {
// ...
});
</script>
Is there any drawback to the second approach, or is it definitely the way to go when the javascript action is not tied to a URL?
Note: I've read this similar question, but the poster was asking about removing the href
attribute, still keeping the <a>
.
I think one possible reason to use anchor tags is that it is more accessible to users who cannot use a mouse (either due to disability or due to their hardware configuration). When a user tabs through a web page using the keyboard, the browsers tend to jump from one anchor to the next, and might not stop on li tags even if you attach a JS event handler to it.