Understanding Events-Part 2

Rajashree Parhi
Behind the Tech — Chainwhiz
5 min readAug 26, 2022

Written by — Rajashree Parhi | Edited by — Arka Sengupta

Let’s recapitulate what we learned so far:

  1. Events are occurrences in the system that informs us of the action to be taken.
  2. Event handlers are part of the code that handles the events happening.
  3. addEventListener() helps us to register event handlers on the web pages.
  4. removeEventListener() is the reverse of addEventListener() which stops the code from listening. We use it to clean up extra resources to avoid memory leaks.

But, this is just the tip of the iceberg!

We can even register event handlers using- event handler properties and inline event handlers.

Wait, what are Event handler properties?

Elements that have the capabilities to fire events also have a set of properties following the name pattern of ‘on……’

For example, elements have property onclick. This is a classic example of an event handler property. To listen for the event, we can assign the handler function to the property, as follows —

But there’s a catch. Unlike in the case of addEventListener(), with event handler properties we can’t add more than one handler for a single event. It overwrites the earlier ones. (bummer, I know..)

Here are the various event attributes that can be added to HTML elements to define event actions — https://www.w3schools.com/tags/ref_eventattributes.asp

Inline event handlers

Inline event handlers register the events for the HTML attributes in the HTML and have the handler in the <script>.

<button onclick=”changeText()”>Click me</button>

The above code invokes the function changeText() defined in the eventHandler.js script.

Warning: One should never use inline event handlers because it makes the code difficult to maintain, hence it’s considered as a bad practice.

Event objects

You might have noticed we pass a parameter like ‘event’, ‘evt’ or ‘e’ inside the event handler function. It is known as an event object which is automatically passed on to the event handlers to provide extra features and information.

We can rewrite the above code by using the event object, as follows:

Let’s break-down the above code-

e.target references to the element the event occurred upon. So, in this example, e.target points to the button and by using innerText we are being able to modify the text.

Note: The parameter name can be anything but e/evt/event are common practices.

Most event objects have a standard set of properties and methods available on the event object. Click here to learn more about the Event objects.

Up next, we have Event bubbling and capturing

Let’s look at an example-

If I click on the button, this is the output:

However, if I click just outside the button, the output changes to-

Looks strange, doesn’t it? But, before diving into the explanation, let’s decode more of the event object properties shown in the image(s) above:

  • e.target: As mentioned above, it refers to the DOM element from where the event was triggered.
  • e.eventPhase: Shows the current phase of the event propagation(3 →bubbling, 2 →target and 1 →capturing) i.e the sequence by which the event handlers are called.
  • e.currentTarget: It refers to the DOM element with an event handler attached.

Event bubbling and capturing

https://blog.logrocket.com/deep-dive-into-event-bubbling-and-capturing/

When an event is fired on an element that has parent elements,(in my code <button> has <div> as the immediate parent), browsers run three different phases- the capturing phase, the target phase, and the bubbling phase.

Phase 1- Capturing phase:

  • The browser searches if the element’s outermost ancestor has any event handlers registered on it for the capturing phase. If found, it gets executed.
  • It trickles down to the next element and the same thing continues happening until it reaches the direct parent of the element.

Phase 2- Target Phase:

  • The browser checks if the target property has an event handler and runs it, if so.

Phase 3- Bubbling Phase:

  • The bubbling phase is the exact opposite of the capturing phase.
  • The browser checks if the direct parent has an event handler registered on it for the bubbling phase. If it’s there, it gets implemented.
  • Then it moves up in the hierarchy executing the event handlers in a similar way until it reaches the outermost ancestor.

Now the next question that comes to mind is that in the examples above I can’t see event capuring i.e event phase 2 in the output. So, where did it go?!

As we can see from the above images/ code snippets, the event propagation is listened to using addEventListener(). In my last article, I explained that addEventListener() takes in two parameters but can accept a third parameter! 😅 It takes in an optional capture value which is set to false by default.

element.addEventListener(<event_name>, <event-handler>, false)

In my examples, the event handler gets executed for the bubbling phase since the third parameter is missing in all the handlers defined which is the default behaviour.

When the button is clicked, the event bubbles from <button>. It first runs the handlers on it, then on its parent i.e <div>, and then all the way up to other ancestors.

https://javascript.info/bubbling-and-capturing

But, if we had passed on the third parameter as true, the event handlers would have got executed for the capturing phase.

How to stop event bubbling?

In the above example, I clicked on the button but the <div> colour changed which seemed strange, right?

This can be prevented by using stopPropagation() which when invoked on a handler’s event object prevents the event from bubbling up on the other chain.

This means that all the listeners registered on the nodes on the propagation path that follow the current target will not be called. Instead, all the other remaining listeners attached to the current target will still receive the event.

We can fix it by adding e.stopPropagation() in the btn handler-

Output-

Conclusion

Event bubbling and capturing are essential concepts in the JavaScript world. With that, I hope I have shown how it works. If you want to play around more, please head over to the link- https://github.com/rajashree23/events 😃

In my next article, we will see how we can create our own custom events!! 😜

Link to the first part- https://medium.com/behind-the-tech-chainwhiz/understanding-events-part-1-6624900e3f4

--

--