Returning false
to a jQuery event handler is the same as calling event.preventDefault()
and event.stopPropagation()
(where event
is the received object as a parameter).
Then:
-
event.preventDefault()
prevents the default event from occurring (eg follow a link);
-
event.stopPropagation()
prevents the event from being propagated to the handlers of parent DOM elements;
-
return false
does both (and still stops executing the handler immediately, without executing the instructions that come after).
(Source: link )
For example, suppose you have the following HTML snippet:
<div id="main">clique<a href="teste">aqui</a></div>
And now you install two handlers:
$('#main a').click(function(event) {
alert('main a');
});
$('#main').click(function(event) {
alert('main')
});
When you click on the link, the two handlers will be executed and soon you will be redirected to the "test" page (this is the default behavior of a link).
Using only event.preventDefault ()
$('#main a').click(function(event) {
// impede o comportamento default (ir para página "teste")
event.preventDefault();
alert('main a');
});
In this case, event.preventDefault()
prevents you from being redirected, but the other handler will still be executed.
Using only event.stopPropagation ()
$('#main a').click(function(event) {
// impede de propagar o evento para os elementos pais (ex.: #main)
event.stopPropagation();
alert('main a');
});
The second handler will no longer run, but you will still be redirected.
Using the two or with return false
$('#main a').click(function(event) {
alert('main a');
return false;
});
If, however, you call event.preventDefault()
and event.stopPropagation()
(or, equivalently, only return false
), the first event handler will be called but, however, the event will not propagate to the second handler .
Thinking about the most common cases, stopPropagation()
is useful for links, which have an associated default behavior, but not so much for pure text (after all, the browser does nothing special when you click on the text). >
preventDefault()
is useful when you have multiple handlers and want an element to have a unique behavior, without inheriting the behavior of the elements it contains.