return false; at the end. Why? What does it do? The answer is: It depends. Before we get into the details, there are basically two things it could be doing:
- Preventing the default action of the event, such as when you click a link and the browser follows it.
- Stopping propagation of the event to ancestor elements.
So which does
return false do? Just one, neither, or both:
- DOM0 handlers: In an old-style DOM0 handler, hooked up via an attribute like this:
...it prevents the default action but doesn't stop propagation. Note that you need that
<div onclick="return functionName();">
returnin the attribute. Try it here.
- DOM0 handlers (again): The same is true of an old-style DOM0 handler hooked up via the reflected property for the attribute, like this:
Try it here. As before,
document.getElementById("someId").onclick = functionName;
return false;prevents the default action but doesn't stop propagation.
- DOM2 handlers: In a proper DOM2 handler hooked up via
addEventListener, like this:
document.getElementById("someId").addEventListener("click", functionName, false);
return falsedoes absolutely nothing. Instead, use the
stopPropagationfunctions on the
Eventobject your handler receives as an argument. Try it here (be sure to use a non-Microsoft browser, or use IE9 or higher).
- Microsoft DOM2-ish handlers: In a DOM2-ish handler hooked up with Microsoft's
attachEventfunction, like this:
return falseprevents the default but not propagation, just like a DOM0 handler. Try it here (using IE8 or lower).
- jQuery handlers: Event handlers hooked up with jQuery get a twofer:
return falseboth prevents the default and stops propagation. It's a jQuery thing.