Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 520
Matt Dawdy Avatar asked Dec 05 '22 07:12

Matt Dawdy


1 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>
like image 149
nickf Avatar answered Dec 24 '22 13:12

nickf