If I remember correctly you need to use a closure or the code will execute directly.
This is how I usually do it.
document.querySelector('#check').addEventListener('click', function(el) {
console.log(el.target);
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have an older app that I am rewriting some code in. I had some inline onclicks and changing to addEventListener.
Old
<?php if ($row['isclr'] == 1) { ?>
<td onclick="handleClick(this)"><input type=checkbox name=isclr id=isclr value=1 checked=checked /></td>
<?php } else { ?>
<td onclick="handleClick(this)"><input type=checkbox name=isclr id=isclr value=0 /></td>
<?php } ?>
Function:
function handleClick(e)
{
const isclr = e.parentNode.dataset.isclr;
more code
New
<?php if ($row['isclr'] == 1) { ?>
<td class="hclr"><input type=checkbox name=isclr id=isclr value=1 checked=checked /></td>
<?php } else { ?>
<td class="hclr"><input type=checkbox name=isclr id=isclr value=0 /></td>
<?php } ?>
Code for function:
document.querySelectorAll(".hclr")
.forEach(hclr => hclr.addEventListener("click", e => handleClick(hclr)));
function handleClick(hclr)
{
const isclr = hclr.parentNode.dataset.isclr;
more code
Everything works but the ide shows the above e (not used). I tried without the e like:
("click", handleClick(hclr)
But that doesn't work. In the above is the e correct and it just an ide false positive? And is there a better way to use the addEventListener?
Thanks
Just do it like this without passing e to the callback
document.querySelectorAll(".hclr") .forEach(hclr => hclr.addEventListener("click", () => handleClick(hclr)));
Please or to participate in this conversation.