Wednesday 16 May 2007

A comprehensive review of how to make an anchor tag do nothing

What's the best way to fire a javascript event from an anchor tag without mucking up your navigation? For that matter, what's the best way to do anchor tags all together? Have a look at the tests below and review the source before making your own decision (you might want to copy the source out to your html file).

Here's a few things to consider:

  • We do not usually want a link to return the caret to the top of the page.
    Javascript may be disabled on the client side (but all solutions presented here are javascript-dependent)
  • Microsoft apparently recommends against using javascript: calls from within the HREF element of an anchor tag and its use may also impact accessibility.
  • If using a click event handler, place a hash in the href attribute and a return false; as the final code for the onClick attribute; ensure any preceding function calls can be interpreted and executed or the return false may never be reached.
  • Alternatively, use another tag (not an anchor tag) and its onClick attribute.

a (without href) (no underline)
a href="" (normal link)
a href="" (opens containing folder in IE (when run without a web server); scrolls to top of page in FF)
a href="#" (scrolls to top of page)
a href="javascript:" (works in IE but pops up javascript console in FF)
a href="javascript: return false;" (javascript error)
a href="javascript: void(0);" (works but may cause problems)
a href="javascript: myFunc();" (works if myFunc () is defined - myFunc does not need to return false)
a href="javascript: myUndefinedFunc ();" (javascript error)
a href="top" (scrolls to top of page)
a href="null" (no underline)
* a href="#bookmark" (works if a name is defined immediately above)
a onclick="return false;" (without href) (no underline)
a href="" onclick="return false;" (works)
a href="#" onclick="return false;" (works)
a href="#" onclick="myBrokenFunc; return false;" (javascript error and scroll to top because return false never executes)
a href="#" onclick="myOnClickFunc (); return false;" (works)
* styled span (works but doesn't "select" on click or change color on visit)

* = A preferred way to do nothing links

1 comment:

Spam comments will be deleted

Note: only a member of this blog may post a comment.