JavaScript-only Links
JavaScript-only interfaces often have some links that activate some kind of click handler but don't actually go to another page. These are called JavaScript-only links, and there are a bunch of different ways to make them, listed here from crappiest to best:
<a href="#" onclick="myFunc();return false">
This method is really common, and not that great. If you are scrolled down the page, and forget to include the
return false
, the page will jump up to the top. Also, the user will see "#" in the status bar (not a real problem, but kind of messy). The link requires JavaScript to work. It's basically one big workaround for making some text clickable.<a href="javascript:myFunc()">
This method gets a lot of slack, but I think it's slightly better than using
href="#"
. True, it's a totally invalidhref
attribute, and it's pure luck that browsers actually support thejavascript:
protocol. But it works (if you have JavaScript enabled). And it has a slight benefit (or downside?) that users actually see the name of the function in the status bar, giving them a clue as to what is going on. You also don't need to worry about returning false from the click function.<a href="#myFunc" onclick="myFunc()">
Very similar to using
href="#"
, this method actually changes the URL to something slightly meaningful. This method can be useful if it changes the page in a repeatable way (displaying a specific tab or hidden area). This way you can add JavaScript that looks in the URL, sees the #myFunc, and recreates that change when the user refreshes the page. If you're tricky, you can even get the back and forward buttons to work. The downside: if the user has scrolled down, the page will scroll back to the top.<span onclick="myFunc()" style="text-decoration:underline; color:#00f; cursor:pointer">
This is my favourite obtrusive method. If you're going to make a JavaScript-only link, why use a link at all? Anything can be clickable in JavaScript, and using CSS you can make a span look exactly like a link (even the mouse cursor). Downside: this method is still obtrusive, requiring JavaScript, but at least it's honest about it.
<a href="alternate.html" onclick="myFunc();return false">
This is a highly superior method to the others. If JavaScript is disabled, the link still works, and ideally goes somewhere that does the same stuff that the JavaScript function would do.
Disclaimer: I don't recommend using the onclick
or style
attributes on a regular basis. I also don't recommend making JavaScript-only interfaces ever (unless you have to, and you rarely have to). For more on how not to do all this bad stuff, check out my presentation on Unobtrusive Ajax.