Tuesday, July 3, 2018

Event Bubbling & Event Capturing


ref: https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
ref: https://medium.com/dev-bits/a-perfect-guide-for-cracking-a-javascript-interview-a-developers-perspective-23a5c0fa4d0d

Event Bubbling

Now comes the event bubbling! According to Arun P, a senior software engineer:
“Event bubbling and capturing are two ways of event propagation in the HTML DOM API when an event occurs in an element inside another element, and both elements have registered a handler for that event. The event propagation mode determines in which order the elements receive the event.”
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the process is in reverse. We usually attach an event to a handler using the addEventListener function.
addEventListener("click", handler, useCapture=false)
The third argument useCapture is the key. The default value is false. So, it will be a bubbling model where the event is handled by the innermost element first and it propagates outwards till it reaches the parent element. If that argument is true, it is capturing model.
For Ex: Bubbling Model
<div onClick="divHandler()">
    <ul onClick="ulHandler">
        <li id="foo"></li>
    </ul>
</div>
<script>
function handler() {
 // do something here
}
function divHandler(){}
function ulHandler(){}
document.getElementById("foo").addEventListener("click", handler)
</script>
When we click the list element, the order of execution of handlers is like this in bubbling (default) model.
handler() => ulHandler() => divHandler()
In the diagram, handlers are firing sequentially outwards. Similarly, a capturing model tries to fire events inwards from parent to the element clicked. Now change this single line in above code.
document.getElementById("foo").addEventListener("click", handler, true)
The order of execution of handlers then will be:
divHandler => ulHandler() => handler()
You should understand the event bubbling(whether direction occurs towards parent or towards the child) properly to implement the user interfaces (UI) to avoid any unwanted behaviors.
These are the basic concepts in JavaScript. As I initially mentioned, additional to them, your work experience and knowledge, preparation helps you crack a JavaScript interview. Always keep learning. Keep an eye on latest developments(ES6). Dig deeper into various aspects of JavaScript like V6 engine, tests etc. Here are few video resources that will teach you many things.

No comments:

Post a Comment

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...