Difference between preventDefault() and return false()
A lot of people thing 'preventDefault()' is the same as just returning false from something like a link click. It's not. Depending on the application you may see no difference but it does make a difference if the event is bubbled upwards.
by jonathon
HTML
<div id="prevDef" class="parent">
<div>
Oh look at me.
</div>
<a href="#">I'm a link!</a>
<div>
I'm a div, with a link. <a href="#">I'm that link</a>
</div>
</div>
<div id="retFalse" class="parent">
<div>
Oh look at me.
</div>
<a href="#">I'm a link!</a>
<div>
I'm a div, with a link. <a href="#">I'm that link</a>
</div>
</div>
CSS
.parent{
border: 1px solid;
margin: 10px;
}
JavaScript
/* Showing the difference in e.preventDefault() and return false;
Divs are set to turn red on click, links are set to hide
The top div has a link that runs `e.preventDefault()` which means
the link won't navigate away, but it will continue the event flow
(so the div the link is contained in also gets the click event and
turns red).
In the bottom div, the link runs `return false`. This means that the link will hide but stop the event flow going to the div, so the div doesn't recieve that click event.
return false is the same as running e.preventDefault() and e.stopPropogation().
*/
$("#prevDef div").click(function() {
$(this).css({
"color": "#f00"
});
});
$("#prevDef a").click(function(e) {
e.preventDefault();
$(this).hide();
});
$("#retFalse div").click(function() {
$(this).css({
"color": "#f00"
});
});
$("#retFalse a").click(function(e) {
$(this).hide();
return false;
});