Photo by Trevor Brown on Unsplash
Explain onClickCapture in JavaScript
How can I invoke a function if a child element is clicked.
Introduction
Explanation of what
onClickCapture
is and how it differs from theonClick
propertyA brief overview of event propagation in the DOM
Background
A quick refresher on event phases of JavaScript on a browser
There are 3 phases in the lifecycle of an event in JavaScript
Capturing Phase
Target Phase
Bubbling Phase
This what it is looks like on a high level -
But for the scope of this post, we are interested in the capturing phase.
Capturing Phase
An event is in capturing phase when the event goes down to the target element.
As you can see from the above image the Button is the target element, so that event will start flowing from the top that is HTML till the Button.
How the onClickCapture
function fits into the capturing phase
If you notice in the above image, I have declared a function onClickCapture
on DIV which is the parent of Button
So, as per the theory **onClickCapture**
should invoke a function (if any) associated with it while in the capturing phase.
That also means, **onClickCapture
** on DIV will execute before onClick
event of Button.
Here is a CodePen for you to demonstrate the event:
https://codepen.io/sagars_01/pen/oNMZKyY
When it makes sense to use onClickCapture
As front-end engineers most of the time, we tend to use reusable components and most of the time we don’t have any control over the code of the component.
For example, at Lowe’s, we have huge teams which work across different products and we share React Components all the time.
Situation
Imagine yourself in a similar situation where you’re using a button(B1) built by another team and B1 has an onClick method that has an event.stopPropagation(). Your use case is to trigger an API call from your codebase whenever the button(B1) has been clicked.
Note: event.stopPropagation() will stop the event from bubbling.
Solution
In this situation, you can use onClickCapture
on the parent div or tag of the button (B1) to achieve your result.
Example here in JSFiddle
https://jsfiddle.net/sagars71/hzev6um7/
Conclusion
The key takeaways for you are:
There are 3 phases of an event in JavaScript.
onClickCapture works on the Event Capturing Phase
onClickCapture can be used when you want to know if a child element has been clicked.
I encourage you to play with the JSFiddle and try to fit your use case on the same.
Let’s Connect
If you have learned something today, don’t forget to share the post with your friends, colleagues and anyone who can benefit from this. This will motivate me to write more for you.
Do follow me on social, I post regularly on JavaScript, Software Engineering and Distributed System Designs. Twitter LinkedIn