Reputation: 4344
I don't have an example at hand, but in some situations calling event.preventDefault()
lets the original event through (navigating to page, submitting form etc) but returning false helps. What could cause this?
Upvotes: 0
Views: 1189
Reputation: 150080
You don't have an example to hand? OK, let me invent one that may or may not be whatever it was you were thinking of.
Remember that return false;
is the equivalent of calling both event.preventDefault();
and event.stopPropagation()
. EDIT: This applies with jQuery, which explictly implements this behaviour and also normalises event.preventDefault()
and event.stopPropagation()
for use in all browsers. It doesn't work that way in all browsers with "plain" JS, in fact older IE versions don't support event.preventDefault()
at all, they have their own equivalent event.returnValue = false;
If you have nested elements and you handle the same event in several levels then calling event.preventDefault()
will not stop the outer elements' event handlers from running, but return false
will because it stops propagation of the event.
An example that demonstrates it: http://jsfiddle.net/nnnnnn/KjLv3/
<a href="#"><span>Click me to see an alert</span></a>
// using jQuery for simplicity in the example:
$("a span").click(function(e){
e.preventDefault();
});
$("a").click(function() {
alert("Hello");
});
The alert will display. If you change the "a span" handler to return false the alert will not display.
Upvotes: 2
Reputation: 100205
event.preventDefault() prevents the browser from performing the default action ( if the event is cancelable ) without stopping further propagation of the event, whereas return false prevents the event from propagating (or "bubbling up") the DOM, along with preventing the default action.
So,
function() {
return false;
}
// IS EQUAL TO
function(e) {
e.preventDefault();
e.stopPropagation();
}
Upvotes: 1