tags:

views:

99

answers:

5

Is there any difference between

1 : <a href="javascript:MyFunction()">Link1</a>

and

2 : <a href="#" onclick="MyFunction()">Link2</a>

? Would one affect the page performance by any means ?

+5  A: 

No performance difference.

The first is crap because it will fail completely for users without JS enabled.

The second is still crap, but would be better if the href pointed to a URL for users without JS enabled.

Coronatus
A: 

There is a difference in functionality, the first doesn't attempt to process a link. The second does.

However, I agree with Coronatus - both methods are not ideal. I would suggest researching unobtrusive JavaScript (perhaps with jQuery) as you could dynamically add a click event to the element.

Mayo
+7  A: 

If your element is not actually supposed to link the user someplace, don't make it an anchor element. If you're using <a> tags just to get the underline/cursor change - don't. Use CSS on a <span> (or other element) instead.

span.link {
  text-decoration: underline;
  color: blue;
  cursor: pointer;
}

Keep your HTML semantic and use anchor elements only when you want to link the user somewhere.

Peter Bailey
+1  A: 

The onclick version allows you pass 'this' as an argument, so you can refer back to the tag/object the click came from. Not possible with the protocol method:

<a href="#" onclick="alert(this.innerHTML)">yo yo yo</a>

will spit out an alert popup with "yo yo yo", whereas

<a href="javascript:alert(this.innerHTML)">yo yo yo</a>

will spit out 'undefined'.

Marc B
+1  A: 

An href="javascript: doSomething" means you do not have a url to fallback to if the user doesn't have js enabled.

Therefore, setting href="something.html" and onclick="return doSomething()" is usually considered better because if js is disabled, you can navigate to a new page, but if js is enabled, you can return false to prevent navigation to the link and display something within the same page without a page refresh.

Even better, don't add the onclick inline, just add js handlers when the page loads. That's the unobtrusive way

Juan Mendes