Search code examples
javascripttestingaddeventlistenerdom-events

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


Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the 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 a 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]", the event fires well, but the "Test link 2" always reports false. Can somebody help?


Solution

  • 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).