Maik Lowrey
Maik Lowrey

Reputation: 17586

Click EventListener does not work if the child element is disabled

Target

I want the parent element to be clickable even though the child element is disabled.

Example Code

const parent = document.getElementById('parent');

parent.addEventListener('click', (e) => {
  console.log('hello world')
}, true);
<div id="parent">
  <input disabled placeholder="foo">
</div>

Important Note

@Drag13 had pointed out to me that it works in Chrome 96. It does not work in Firefox 95.0 on Linux OS.

Thanks in advance!

Upvotes: 5

Views: 267

Answers (1)

Maik Lowrey
Maik Lowrey

Reputation: 17586

It is a Firefox problem and even an older one. In the Chrome browser, on the other hand, it works as expected. To get around the problem, you can use a little trick.

Add the CSS property: pointer-events:none; to the disbaled impunt field. This delegates the click to the parent element. The click is evaluated again in the parent element and should therefore work. Special thanks go to @aerial301.

const parent = document.getElementById('parent');

parent.addEventListener('click', (e) => {
  console.log('hello world, now it works :-)')
}, true);
input[disabled] {
    pointer-events:none;
}
<div id="parent">
  <input disabled placeholder="foo">
</div>

Upvotes: 4

Related Questions