Many times I've seen links like these in HTML pages:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
What's the effect of the return false
in there?
Also, I don't usually see that in buttons.
Is this specified anywhere? In some spec in w3.org?
You can see the difference with the following example:
Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.
Return false will prevent navigation. Otherwise, the location would become the return value of someFunc
Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.
In other words, adding return false stops the href from working. In your example, this is exactly what you want.
In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.
I am surprised that no one mentioned
onmousedown
instead ofonclick
. Theonclick='return false'
does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for
mousedown
butonmousedown='return false'
does.
In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the
mousedown
event is registered beforeclick
, so if you only prevent that behaviour inside yourclick
handler, it will not affect the unwanted selection arising from themousedown
event. So the text still gets selected. However, preventing default for themousedown
event will do the job.See also event.preventDefault() vs. return false
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.
The modern way of achieving this effect is to call
event.preventDefault()
, and this is specified in the DOM 2 Events specification.