views:

468

answers:

5

I've recently been bitten by the javascript:void(null); bug in my hrefs when applied to images.

In my version of Safari (4.0.3 in Leopard PPC) when I apply an href of javascript:void(null); around an image, the image completely disappears from the layout. Looking around I see this happens in IE as well though I cannot confirm.

I've read using the pound sign (#) with an onclick handler

onclick="return false;"

This works, but I hate having the pound appended to the url.

I know there are various techniques, So how do you handle your hrefs?

+1  A: 

I put valid URLs in my hrefs. Why are you making links that don't do anything?

 <span onclick="doSomething();" class="fakeLink"><!-- active elements --></span>
Scott Saunders
Mainly for event handling which you'd want to force the link to do nothing.
Richard Testani
Sure. But it's not really a link then is it? Using the <a> tag introduces headaches like the one you're dealing with now - where to point the link, what if js is not enabled, etc. Using <span> or <div> tags avoids those headaches at the expense of adding some css to style the fakeLink class to look like your links. But if you're styling your links anyway, that's not much additional work.
Scott Saunders
+3  A: 

Like this

<a href="#" onclick="doSomething(); return false;">

Or preferably

<a href="nonJavascriptAlternative.html" id="foo">

then attach a handler with javascript - in jQuery

$('foo').click(function() { doSomething(); return false; });
Greg
+1  A: 

Don't use # for the reason you mentioned and on some browsers, if the user is scrolled away from the top clicking the link will jump them back to the top. I use this:

<a href="javascript:"><img src=""/></a>

That shouldn't cause a problem on any browser (at least I haven't had a problem yet).

Karim
It will fire the event "onbeforeunload" on IE, I preferably use "#1", that won't scroll to the top and will never match any ID or name in the DOM
Fabien Ménager
Did not know that. IE strikes again.
Karim
+1  A: 

If you return false onclick, the click action is cancelled so # won't be appended to the url

<a href="#" onclick="return false;">
adam
+3  A: 

My preferred option is

<a href="non_javascript_alternative.html" onclick="doSomething(); return false;">

... where possible (which isn't always). Having the event handler in the attribute has the following benefits over attaching the event after the document has loaded:

  1. Simplicity
  2. Clarity
  3. Compatibility
  4. JavaScript event handler will function even before the document has loaded.
Tim Down
How is this the *worst* answer here?
Tim Down
It's not - I was about mark this answered. I think its the best answer for its flexibility and clarity. Just am getting to it :)
Richard Testani
Sorry for the flouncy hissy fit :)
Tim Down