I do not intend to start a debate.
If we want to make use of the onClick event, we should, on a certain way to disable the href to trigger. - Is this correct ?
If the above is correct, I believe that javascript:void(0)
has the advantage of NOT triggering the scroll behavior.
Are those assumptions correct?
Note: I do not intend to search for a chimera, but my quest is about finding a way to style buttons in a cross-browser way with no accessibility hit (at all), without hacks and quirks.
If you have to have an href, use
javascript:void(0)
, because it has no effect, unlike#
. But you can just have no href at all, give thea
aclass
to make it look like a link, e.g.:If you want to prevent following the link, you should add
event.preventDefault()
in your click handler (event.returnValue = false;
in IE).It seems that you are just after the look of a link and not its functionality (or purpose). If so, you can use a
button
with CSS to style it accordingly.Having real links with href contents
#
orjavascript:void(0)
should be avoided.Further explanation:
Using a link just to have something "clickable" is not good. A link has a distinct syntactical meaning. As you can assign a
click
event handler to every element, you can use any other element for that.The syntactically most correct one (imo) would be
button
as you will still have the possibility to usetab
to navigate on them. You can style them with CSS to make them look like a link if you want to (see this example).Now regarding preventing the default action:
Assuming you have a normal link with a proper
href
value and you want to intercept the click. In the click handler you assign to the element, e.g.using
event.preventDefault()
prevents the default action, which in case of a link, is following the URL.(the code above is an example for W3C compatible browsers, IE is a bit different)
I prefer javascript:void(0) over # because it does not alter the address bar by putting a # there (which may affect any future scripts that use/alter the URL).
But better than both of them, I prefer to have the onclick function return false (so it doesn't navigate at all) and then put an URL that would result in the same action as clicking. For example, lets say clicking the link loads some content into a 'mainArea' div. Then the URL would reload the whole page, with that mainArea filled with the same thing. The advantage to doing this is that if they right-click the url and Copy Address or Open in New Tab, it still works.
If you want to seperate markup and scripting, you might also consider using event delegation to set-up the event handlers.
Many Javascript frameworks (eg jQuery) come with cross-browser abstractions to make this less of a bother; because of NIH-syndrome, I rolled my own solution, though.
A complete example could look like this: