Hello everyone, I’m Daotin, the leader of the front end. If you want to get more wonderful content of the front end, please follow me (with the same name on the whole web) and unlock the new pose of the front end growth.

The following text:

stopPropagation

Prevents bubbling and capturing of events.

Because events can be passed between nodes at all levels, whether bubbling or captured, sometimes we want the event not to be passed after the execution of a particular node, we can use the stopPropagation() method of the event object.

preventDefault

Prevents browser default behavior.

Browser default behavior: The browser has its default behavior for certain events.

Such as:

  • Clicking on the link will lead to a jump
  • Clicking the right mouse button will bring up the browser right-click menu
  • Press enter when filling out the form and it will be automatically submitted to the server, etc

return false;

When you call it, it does three things:

  • Event.preventDefault () – This stops the default behavior of the browser.
  • Event.stopPropagation () – This prevents events from propagating (or “bubbling”) the DOM.
  • Stop callback execution and return immediately.

For example, you can prevent the default jump event for the a tag by returning false, or you can use preventDefault() instead.

Table comparison:

methods Event bubbling/capture The default event
stopPropogation() Don’t bubble perform
preventDefault() The bubbling Does not perform
return false Don’t bubble Does not perform

Immediacy of stopPropagation for each person

  • The common denominator can prevent the event from bubbling, and the parent node cannot accept the event.
  • The difference betweenstopPropagationDoes not affect theThis element follows the execution of the same event, whilestopImmediatePropagationThis prevents subsequent execution of the same event for the element.

Example:

<div>
  <p>Daotin</p>
</div>

Bind p with a click event, p with a second click event, and div with a click event.

If in p’s first click event callback stopPropagation, div’s click event callback is not executed, but p’s second click event callback is executed.

If there is stopImmediatePropagation in the first click event callback of P, the callback of div’s click event is not executed, and neither is the second click event of P.

— End —

Hello, I’m Daotin, the front-end leader, focusing on sharing front-end and cognition. I hope to share my front-end learning and working experience with you here, and record my personal growth.

Want to get more front-end exciting content, pay attention to me (the whole network with the same name), unlock the front-end growth new posture.