How to check whether dynamically attached event listener exists or not?

Stano picture Stano · Jul 12, 2012 · Viewed 181.9k times · Source

Here is my problem: is it possible somehow to check for existence of dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in DOM? I have searched internet just like Stack Overflow for a solution, but no luck. Here is my html:

<a id="link1" onclick="linkclick(event)"> link 1 </a>
<a id="link2"> link 2 </a> <!-- without inline onclick handler -->

Then in Javascript I attach dynamically created event listener to the 2nd link:

document.getElementById('link2').addEventListener('click', linkclick, false);

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?

jsFiddle is here. If you click "Add onclick for 2" and then "[link 2]", event fires well, but the "Test link 2" always reports false. Can somebody help?

Answer

Ivan picture Ivan · Jul 12, 2012

There is no way to check whether dynamically attached event listeners exist or not.

The only way you can see if an event listener is attached is by attaching event listeners like this:

elem.onclick = function () { console.log (1) }

You can then test if an event listener was attached to onclick by returning !!elem.onclick (or something similar).