3

Possible Duplicates:
What's the effect of adding 'return false' to an onclick event?
When and why to 'return false' in javascript?

I mean, if I have this function :

 function openMask() {
     alert("enter");
 }

is it better call it as :

 <a href="javascript:void(0);" onclick="openMask()">Link</a>

or :

 <a href="javascript:void(0);" onclick="openMask(); return false;">Link</a>

??? I'm really curious about it! Never understood the difference...

Community
  • 1
  • 1
markzzz
  • 47,390
  • 120
  • 299
  • 507

4 Answers4

4

In a DOM event handler (such as onclick), returning true means "continue with the event", and returning false means "don't".

In this case, it's not entirely meaningful because your href is already javascript:void(0) (which won't do anything).

Note, though, that javascript: URIs should really be avoided, and that this isn't very helpful for non-Javascript users, so you should provide a fallback page, and then the return false becomes more meaningful:

JS:

function openMask() {
   alert("enter");
   return false; 
}

HTML:

<a href="fallbackpage.html" onclick="return openMask();">Link</a>
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

The best would be to use:

 <a href="/page/with/opened/mask" onclick="openMask(); return false;">Link</a>

So users without JavaScript (including Google Bot) can use your site.

Tomasz Wysocki
  • 11,170
  • 6
  • 47
  • 62
1

return false causes the browser to ignore the href. In your specific example it changes nothing since the href does nothing, but it would matter if you had something like href='#'

orip
  • 73,323
  • 21
  • 116
  • 148
  • And is better write `javascript:void(0);` or `javascript:void(0)` (with or without `;`)? – markzzz Aug 21 '11 at 12:54
  • @markzzz: The best is to have a proper URL: http://stackoverflow.com/questions/4842953/or-javascriptvoid0 . What if JavaScript is disabled? Your link won't do anything. – Felix Kling Aug 21 '11 at 12:54
  • @Felix Kling : what do you mean? I won't to link to any ways... – markzzz Aug 21 '11 at 12:56
  • 1
    @markzzz: Then why do you use a link at all? That's their only purpose, to link to somewhere. If you just want to have something clickable, use a button and style it according to your needs. A button would be the semantically most correct element in this situation. – Felix Kling Aug 21 '11 at 12:57
  • You can style a button as a link (on IE7 for example). Just check this http://jsfiddle.net/NcCVj/3/ : you will see sme margin/padding on IE7 that shouldnt be presents... – markzzz Aug 21 '11 at 14:31
1
return false   

means prevent the default behavior of an event. in your example, that's prevent the browser to open the url of link

wong2
  • 34,358
  • 48
  • 134
  • 179