2

I was just woundring what is the prefered way of skipping the behavior that the browser changes the location when clicking on a link element (A) with inline code.

<a href="javascript:void(0)">void(0)</a> // I have always used this one

Or

<a href="javascript:;">:;</a> // This one is simple and now a days my favourite

Or

<a href="#">#</a> // Scroll to the top

Or how do you do, and WHY? What is best practies?

Simon Edström
  • 6,461
  • 7
  • 32
  • 52

3 Answers3

0

It depends on why you want to skip the default behavior. With the methods you show above, the links aren't very useful, because their href attributes don't contain any information. They're just placeholders...you could just as well refer to a nonexistent ID, <a href="#phlogiston">dummy link</a>, and it will do nothing when clicked.

If you want a link to have a normal href attribute but to do something else when clicked, you wouldn't do it inline. Instead you would call the event.preventDefault() method whenever the link triggers a click event, using a script loaded by the page. Also see this answer: event.preventDefault() vs. return false

Community
  • 1
  • 1
Peter Behr
  • 607
  • 1
  • 5
  • 16
0

I prefer to use onclick instead of the href javascript tag. But if you have to, return false. It will stop the browser from its default action (changing the URL). There's also no down side I'm aware of with to the two first. Avoid the third one, it can cause page scroll on very long pages and pollute the navigator history.

<a href="javascript:dostuff(); return false;">Do nothing</a>
werfu
  • 382
  • 1
  • 11
0

Personally, I prefer to "inject" actions to the links instead of mixing js and html. You don't have to scan HTML for javascript behaviors that way.

A quick example using jQuery: http://jsfiddle.net/5nbXT/

Thach Mai
  • 915
  • 1
  • 6
  • 16
  • I don't know, but I think that this couse an extra overhead to client couse it has to serach for all the elements within the selector and attatch the event handler. – Simon Edström Apr 23 '12 at 19:08
  • @SimonEdström Of course if you're purist, this technique would probably add a few nanoseconds of processing time on load... But honestly, DOM transversing is so fast these days, this is virtually indistinguishable from the inline version. – Thach Mai Apr 23 '12 at 19:31