Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jquery
event handlers
prevent default
stop propagation
return false

Difference between preventDefault, stopPropagation & return false

Educative Answers Team

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 false is a combination of both preventDefault() and stopPropagation().

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:

  1. Use neither of the three statements (comment out lines 4-6 in JavaScript)
    In this case, when the hyperlink element is clicked, we are redirected to educative.io. Moreover, we observe all three alerts for div, p, and a due to event propagation.

  2. Use eventObj.preventDefault() only (uncomment line 4 in 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.

  3. Use eventObj.stopPropagation() only (uncomment line 5 in 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 for div and p due to stopPropagation().

  4. Use return false only (uncomment line 6 in 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 for div and p because we now get the functionality of both preventDefault() and stopPropagation().

  • HTML
  • JavaScript

RELATED TAGS

jquery
event handlers
prevent default
stop propagation
return false
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring