Hi, I’m Daotin, the front end team leader. If you want to learn more about the front end, follow me and unlock the new front end growth posture.

The following text:

stopPropagation

Prevents events from bubbling and capturing.

Because events can be passed across all levels of nodes, whether bubbled or captured, sometimes we want events not to be passed after a particular node has executed, we can use the stopPropagation() method of event objects.

preventDefault

Block browser default behavior.

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

Such as:

  • Click on the link to jump

  • Click the right mouse button to call out the browser right menu

  • When filling in the form, press Enter and it will be automatically submitted to the server

return false;

When you call it, it does three things:

  • Event.preventdefault () – It stops the browser’s default behavior.

  • Event.stoppropagation () – This prevents event propagation (or “bubbling”) to the DOM.

  • Stop the callback execution and return immediately.

For example, return false to prevent the a TAB’s default jump event, or preventDefault() instead.

Table comparison:

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

Add: The difference between stopPropagation and stopImmediatePropagation

  • Common to prevent events from bubbling, the parent node cannot receive events.

  • Different stopPropagation does not affect the subsequent execution of the same events for that element, while stopdynamic Propagation prevents the subsequent execution of the same events for that element.

Example:

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

Copy the code

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

If stopPropagation is performed on the first click callback of p, the div click callback will not be executed, but the second click callback of P will be executed.

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

— End —

Hi, I am Daotin, front end team 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.

For more front-end highlights, follow me and unlock new front-end growth poses.