jQuery: Difference between "return false" and "event.preventDefault()"
Info by Progger99 | Last update on 2023-01-29 | Created on 2012-05-30
In JavaScript jQuery code, some seem to use a "return false" and an "event.preventDefault()" interchangeably. But what is the exact difference between these two lines of code?
An Example
First, we want to have a look at an example with "return false":
$("a").click(function() { return false; });
And here is an example with event.preventDefault():
$("a").click(function(event) { event.preventDefault(); });
Both examples make sure that the actual action (clicking on an a-element is calling the appropriate link) is suppressed. But what is the difference?
The Difference
The difference is that a "return false" has further reaching consequences than a preventDefault(). A preventDefault() merely provides that the default action is not executed, a return false in jQuery, however also ensures that a stopPropagation() is executed. This means that a performed action such as a click on an element is not given further to the underlying elements.
Therefore, the code:
function() { return false; }
Is the same as:
function(event) { event.preventDefault(); event.stopPropagation(); }
However, only in jQuery! Within JavaScript in normal non-jQuery event handlers "return false" does not have this effect, and also after a "return false" the action is passed there anyway.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
JavaScript: Catch Submit of Form
Tutorial | 0 Comments
jQuery: Assign Action to Keyboard Keys (Keyboard Event)
Tip | 0 Comments
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Remove Spaces from the Beginning and End of the Lines of Texts
Tutorial | 0 Comments
Delphi: Event Order of a Form - From OnCreate to OnDestroy
Info | 1 Comment
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.