Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 844
Maik Lowrey Avatar asked Nov 05 '22 23:11

Maik Lowrey


1 Answers

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>
like image 96
Maik Lowrey Avatar answered Nov 12 '22 09:11

Maik Lowrey