wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes return false Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "return false" Watch "return false" New topic
Author

return false

Grega Leskovšek
Ranch Hand

Joined: Nov 13, 2008
Posts: 53
I am not clear when to write at the end of an action like onclick="javascript code; return false;"
return false?
Thanks in advance, Grega


--Always, Grega from Peace refuge
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
return false cancels the default action. So if you need to cancel the default action you use it.

You should look at the event model

https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

THis is just one reason that embedding behavior in HTML markup is a bad idea. It masks what's really going on.

The value of the attribute becomes the body of an anonymous function. Hence the last "statement" returns the value false form this function.

You should look into the concept of Unobtrusive JavaScript.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
B. Katz
Ranch Hand

Joined: Aug 28, 2009
Posts: 51

Greetings,

If you don't mind me adding my 2 ¢ents here, one good example of where I think you can use "return false;" effectively is to kill the context menu (a.k.a. right-click) of a page when you don't want the users playing around that much.

Example:

HTH.

/me braces for Bear's corrections. ;)


"I do not feel obliged to believe that the same God who has endowed us with sense, reason, and intellect has intended us to forgo their use."
-- Galileo Galilei
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

Sorry but disabling the context menu is a silly thing to do. What purpose could it possibly really serve? Anything that can be done via the context menu can be done by other means that cannot be blocked. So other than to annoy your users, what's the reason?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

B. Katz wrote:/me braces for Bear's corrections. ;)

And not to disappoint:
  • Again, avoid embedding behavior in structure.
  • Don't use all uppercase for HTML. It makes it look like it's from 1998.
  •  
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: return false
     
    Similar Threads
    Appending image to text inside table cell
    stopping event propagation best practice (jQuery)
    Image submit
    AJAX JSP Calendar
    Equals Method Doubt......