Friendlier JavaScript Links

There are two common ways of using JavaScript in a link:

<a href="javascript:doSomething();">Do Something</a> <a href="#" onclick="doSomething();">Do Something</a>

The first one is a bit ugly, since the JavaScript shows up in the status bar. More importantly, neither example will do anything at all if JavaScript isn’t available. This may not be a major concern (simply because it won’t happen often), but it is a concern. I can think of at least a few times where I’d turned JavaScript off, forgotten about it, and was confused as to why a link wasn’t doing anything. Imagine the confusion if someone else had turned JavaScript off. Or worse, if the browser doesn’t support it. I’m sure with all the cellphones, PDAs, screen readers, and plug-it-in-your-TV web browsers out there, some of them do not.

If your JavaScript simply opens a new window, there’s an easy solution:

<a href="dosomething.html" onclick="doSomething();return false;">Do Something</a>

If JavaScript is unavailable, the page dosomething.html will simply open. If JavaScript is available, the doSomething function will run, presumably opening the page dosomething.html in a new window. “return false” tells the browser to ignore the standard link in the href attribute. Without that, the script would run and then dosomething.html would open in the current window… Probably not what you want. Another big advantage with this example is that search engines will also be able to get to all of your pages.

There’s a more common situation though… What if the script doesn’t just go to another page? Most of the time, you’ll just see one of my first examples used… Particularly the second, with that lovely # sign. I have a much better solution, one that I’ve never seen anyone else use:

<a href="javascript.html" onclick="doSomething();return false;">Do Something</a>

What you’re not seeing here is that javascript.html is actually a page explaining that JavaScript is required for certain functions of the site. So when JavaScript is unavailable, instead of doing nothing, a new page loads with a simple message explaining the problem. Search engines will see this page, but a simple meta tag will ensure that they don’t index it:

<meta name="robots" content="noindex,follow" />

You can see this example in use at my own site. Try turning JavaScript off and clicking the “large” or “small” links to change the text size.

Comments

This entry has no comments.

View more

Code

VoiceOver tips for iPhone developers I’ve been working on improving VoiceOver support for Delivery Status touch 3.0. It was…

My First WWDC Above: Apple’s live App Store wall at WWDC. It showed icons of 20,000 iPhone apps,…

Displaying a password or text entry prompt on the iPhone Writing your own iPhone or iPod touch app, and wondering how to create an alert like…

Junecloud: coming soon