Home >Web Front-end >JS Tutorial >`event.preventDefault() vs. return false: When Should You Use Which for Event Handling in JavaScript?`
event.preventDefault() vs. return false in Event Handling
In Javascript, two common techniques exist for preventing subsequent event handlers from executing after a specific event occurs: event.preventDefault() and return false. These methods are available with both jQuery and plain JS.
1. event.preventDefault()
$('a').click(function (e) { // custom handling here e.preventDefault(); });
2. return false
$('a').click(function () { // custom handling here return false; });
Difference between event.preventDefault() and return false
In the context of jQuery event handlers, returning false is essentially equivalent to calling both e.preventDefault() and e.stopPropagation() on the provided jQuery.Event object.
e.preventDefault() prevents the default event from occurring, while e.stopPropagation() prevents the event from propagating up the DOM. Return false performs both of these actions.
However, in regular (non-jQuery) event handlers, return false does not prevent the event from bubbling up the DOM, unlike in jQuery event handlers.
Benefits of using event.preventDefault() over return false
Although return false is generally a simpler and shorter approach, using event.preventDefault() offers additional benefits:
The above is the detailed content of `event.preventDefault() vs. return false: When Should You Use Which for Event Handling in JavaScript?`. For more information, please follow other related articles on the PHP Chinese website!