How can I invoke a function if a child element is clicked.
Explanation of what
onClickCaptureis and how it differs from the
A brief overview of event propagation in the DOM
This what it is looks like on a high level -
But for the scope of this post, we are interested in the 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.
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:
When it makes sense to use
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.
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.
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
The key takeaways for you are:
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.
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.
Did you find this article valuable?
Support Sagar by becoming a sponsor. Any amount is appreciated!