Using an anchor as a javascript action, what should the link be?

I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why?

<a href="" onclick="javascript: DoSomething();">linky</a>

or

<a href="#" onclick="javascript: DoSomething();">linky</a>

Answers


You must have something for the href attribute, otherwise the browser will not treat it as a link (for example, making it focusable or giving it an underline) - that's why the use of "#" has become prevalent.

Also, the contents of the event attributes (onclick, onmouseover, on...) are already treated as javascript: you don't need to preface it with javascript:

So given your example, the best way to do that inline (which itself is not the best way, probably), is like this:

<a href="#" onclick="DoSomething(); return false">linky</a>

Checkout the discussion over at Href for Javascript links: “#” or “javascript:void(0)”?.

Also, leaving href blank causes the browser to not use the pointer cursor when the user mouses over, though you can fix that with CSS.


I always use # as having javascript: inside of html attributes seems to generally be considered as bad practise they days.

So saying that, you should try and refrain from using onclick= attributes and use javascript listeners in external .js files instead.

For example you using jQuery..

$(".link").click(function(e) {
    e.preventDefault();
    DoSomething();
});

Why not have the href point to a page explaining they have JavaScript turned off and they need to turn it on to get the missing functionality ?

Since the link will only be followed when they have javascript turned off, let it be something informative!

Also remember people sometimes middle click on such links and the OnClick event does not fire, so if you can get them a page that works without the need for javascript it would be ideal.


In cases like this, where you intend not to provide a non-javascript option, I prefer:

<a href="javascript:// open xxx widget" onclick="DoSomething();">linky</a>

This way you can at least provide a plan text description as the JavaScript comment.


Need Your Help

django-nonrel specify MongoDB BSON element name to model attributes

python mongodb django-nonrel bson

In C# it is possible to use the MongoDB driver to define a custom BSONElement Name to each attribute in your data models, in order to shorten its stored name, such as

What is the relationship between WebProxy & IWebProxy with respect to WebClient?

c# .net webclient webproxy

I am creating an app (.NET 2.0) that uses WebClient to connect (downloaddata, etc) to/from a http web service.