return false; it's good for you.
Posted Sun, Nov 25, 2007 in:Today I was looking around for blogs about JavaScript when I stumbled upon The Strange Zen of JavaScript by Scott Andrew LePera (Hacker/Singer/Songwriter), which looks to be quite informative, though sadly it seems as though it has been in hibernation since July.
I was relieved to see in reading The Mark Of The n00b that I’m not a n00b (at least according to that particular metric). Though I suppose I should point it out to others so they can avoid being n00bs as well:
use href=“#” and return false from your onclick event handlers to avoid jumping! (Ironically there were comments asking how to avoid the jumping scrollbars in the Mark of the n00b post, which was posted immediately after the return false post. Whoops.) Hopefully adding yet another post about this will help people googling for solutions to this frustrating problem to be more likely to find it.
More about returning false
I hate to just link to a post without adding something to the discussion, so I’ll throw in a bit of extra information about JavaScript event handler return values.
Return values are handy in most any event handler, not just onclick. Returning false prevents the event from “bubbling” up to the browser
Here are some suggestions for ways in which to use event handler return values:
onsubmit
Add an onsubmit handler to a form using onsubmit=“return validate_form()“, if the form input is valid, return true, allowing the form to be submitted. If it is not valid, return false, preventing it from being submitted, then let the user know why.
onmousemove
When using onmousedown and onmousemove to make an element drag-n-drop-able, then you will probably want to return false from the onmousemove handler to prevent any text on the page from being selected.
onmousedown, onmouseup
Say you want to respond to a right click on a link, but you want to leave alone regular left clicks. Register an onmouseup event handler (which takes a parameter e) for that link, check the value of e.button. If it is 0, return true and the link is followed. If it is 2, do your thing (pop up a context menu, perhaps?), then return false so that the browser doesn’t pop up its own context menu. This is the technique used by those annoying scripts that “prevent” you from downloading images from their sites.
For an enormous amount of more information, check out the DOM Event Compatibility Tables over at Quirksmode