I want to capture click event by parent element when a child element disabled, like this codes
document.querySelector('div').addEventListener('click', () => {
alert('clicked!')
// both two ways to stop propagation are useless
event.stopImmediatePropagation()
event.stopPropagation()
}, { capture: true })
<div>
<button disabled>button</button>
</div>
When I click this button, the event will not be captured by div
(standard), but I want this div
to capture this event. How can I do this?
pointer-events:none
does not work for me because I need to usedocument.elementsFromPoint()
to get this button and do something. Andpointer-events:none
will cause the button to not be retrieved by this function
2
Answers
Whenever you are dealing with a scenario where a child element is disabled and you want the parent element to capture click events, then you need to work around the fact that disabled elements do not trigger events in the way enabled elements does.
So in order to achieve this, you can use a combination of event delegation and checking the event target.
You can use the following methods to ensures that the parent element (div) can capture click events even if the child element (button) is disabled:
element (div).
target is a disabled child element.
I am providing one code sample for your reference:
HTML
JavaScritp
I hope this reference code will resolve your query.
If this code resolve your query then kindly upvote my answer.
The button is a child to div.
When a click occurs, div responds first and propagates the event to the button. However, the button is disabled, so there is no response to return it to div, and the event is invalidated.
Some keywords:
Capturing
,Targeting
,Bubbling
If the button is disabled, run the click event in div without passing the event to the button when div clicks.
If not, run a button event.
I recommend you to try more things yourself.