Difference between preventDefault, stopPropagation & return false
preventDefault(), stopPropagation(), and return false statements can all be used in jQuery event handler functions.
preventDefault()prevents the default browser behavior for a given element.
stopPropagation()stops an event from bubbling or propagating up the DOM tree.
Whereas,
return falseis a combination of bothpreventDefault()andstopPropagation().
Implementation
Let’s understand the difference between all three statements with the help of an example webpage.
In the webpage, we have three nested elements: a hyperlink element is nested within a paragraph element and the paragraph element is further nested within a div element. This nesting can also be visualized in the page output. The hyperlink element has the href attribute set to educative.io and, by default, it opens the given website.
In the JavaScript for this webpage, we use jQuery to set up click event handlers for all three elements. Each of the event handlers, upon triggering, displays an alert box with the text specifying which element (div, p, or a) was clicked.
In the click event handler of the hyperlink element, we can have four cases:
-
Use neither of the three statements (comment out
lines 4-6in JavaScript)
In this case, when the hyperlink element is clicked, we are redirected to educative.io. Moreover, we observe all three alerts fordiv,p, andadue to event propagation. -
Use
eventObj.preventDefault()only (uncommentline 4in JavaScript)
In this case, when the hyperlink element is clicked, the default behavior is prevented and we are not redirected to educative.io. However, we still observe all three alerts due to event propagation. -
Use
eventObj.stopPropagation()only (uncommentline 5in JavaScript)
In this case, when the hyperlink element is clicked, the default behavior is not prevented and we are redirected to educative.io. However, we do not observe alerts fordivandpdue tostopPropagation(). -
Use
return falseonly (uncommentline 6in JavaScript)
In this case, when the hyperlink element is clicked, the default behavior is prevented and we are not redirected to educative.io. Moreover, we also do not observe alerts fordivandpbecause we now get the functionality of bothpreventDefault()andstopPropagation().
Free Resources