Feb 072010
 

When using an anchor tag to trigger some javascript why not show it to the user?

For users that don’t look at the status bar they won’t notice or care. For those that do they can see that some javascript is about to be executed, they are looking at the status bar to find out what would happen if they click the link after all. As a bonus you as a developer can now see the javascript call instantly:

<a href="javascript: myFunction();">Click me</a>

Any of these are probably ok depending on what you are trying to do:

<a href="" onclick="javascript: myFunction(); return false;">Click me</a>
<a href="/" onclick="return myFunction();">Click me</a>
<a href="javascript_required.html" onclick="myFunction(); return false;">Click me</a>

The following methods should probably be avoided as they have issues, are outdated or just plain wrong:

<a href="#" onclick="myFunction();" >Click me</a>
<a href="javascript: void(0);" >Click me</a>

On searching the web for best practice in this area I came across this great website which recommends assigning the javascript to the onclick action and pointing the href to a javascript required page. Which is sound advise if you are expecting users that may have javascript turned off. But this is probably getting a bit out dated now since you certainly can’t browse much of the web these days without javascript or flash for that matter. Besides you are using AJAX now aren’t you? So most of the site simply won’t function without javascript turned on. If they are savy enough to turn javascript off then they are savy enough to see ‘javascript:’ in the status bar if we show it to them.

It could be argued that an input button should be used for anything that simply performs an operation on a page and is not intended to be a link. But then it becomes tricky to use an image for the button and a whole lot more css is going to be required. Same with a span, and it will not be added to the tab order.

Besides anchor tags are not called link tags, they create an anchor and the developer can wrap that around other objects like text and images. The default css and pointer also indicate that it is something that a user may want to click, with no further work from the developer required.

Gavin Kromhout:


Thank you for visiting.
Do look around.
Do leave a comment.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)