项目作者: sureshalagarsamy

项目描述 :
JavaScript bubbling and capturing
高级语言: HTML
项目地址: git://github.com/sureshalagarsamy/javascript-bubbling-capturing.git


Bubbling and Capturing

Let’s start with an example.

  1. <div onclick="alert('The handler !')">
  2. <em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
  3. </div>

If you click on EM, the handler on DIV runs.

strange? Why the handler on <div> runs if the actual click was on <em>?

Bubbling

Let’s say, we have 3 nested elements FORM > DIV > P with a handler on each of them:

  1. <form onclick="alert('form')">FORM
  2. <div onclick="alert('div')">DIV
  3. <p onclick="alert('p')">P</p>
  4. </div>
  5. </form>

image

So if we click on <p>, then we’ll see 3 alerts: p → div → form.

image

https://jsfiddle.net/sureshalagarsamy/40yp8mry/

Almost all events bubble.

The key word in this phrase is “almost”.

  1. For instance, a focus event does not bubble.

The most deeply nested element that caused the event is called a target element, accessible as event.target

  • event.target – is the “target” element that initiated the event, it doesn’t change through the bubbling process.
  • this – is the “current” element, the one that has a currently running handler on it.

    Stop bubbling

    A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window

The method for stop bubbling is event.stopPropagation().

  1. <body onclick="alert(`the bubbling doesn't reach here`)">
  2. <button onclick="event.stopPropagation()">Click me</button>
  3. </body>

https://jsfiddle.net/sureshalagarsamy/r91aokzx/

Capturing

There’s another event processing called “capturing”. It is rarely used in real code.

  1. Normally it is invisible to us.
  • Capturing phase – the event goes down to the element.
  • Target phase – the event reached the target element.
  • Bubbling phase – the event bubbles up from the element.

Here’s the picture of a click on inside a table, taken from the specification:

image

Let’s see it in action:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. <style>
  8. body * {
  9. margin: 9px;
  10. border: 1px solid #FF0000;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <form>FORM
  16. <div>DIV
  17. <p>P</p>
  18. </div>
  19. </form>
  20. <script>
  21. for(let elem of document.querySelectorAll('*')) {
  22. elem.addEventListener("click", e => alert(`Capturing: ${elem.tagName}`), true);
  23. elem.addEventListener("click", e => alert(`Bubbling: ${elem.tagName}`));
  24. }
  25. </script>
  26. </body>
  27. </html>

image

https://jsfiddle.net/sureshalagarsamy/rf3wLc5h/