-1

I have an element and I want to know whether or not this element has an event on it? I also want to know what the type this event is.

HTML

<a id="on_btn" href="javascript:;">On</a>

Javascript

document.getElementById('on_btn').addEventListener('click', function(){
    alert('Hello');
})

How to know if the previous <a> tag has an event ? and what the type of event? assuming I don't know.

Notice: I want to use native JavaScript not jQuery.

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Lion King
  • 32,851
  • 25
  • 81
  • 143
  • If you have the chance to actually run code *before* you attach the listeners, you can run this: https://gist.github.com/stringparser/a3b0555fd915138a0ed3. It will attach an `eventListenerList` to every HTML element, and every listener you attach to your elements will be then pushed to that property. Not the best solution, but it might be of use for you. –  May 16 '15 at 23:16

1 Answers1

0

Native javascript does not have a means to query what event handlers are attached to a given object.

If this was some sort of "hacking" project and you could guarantee that you could runs some Javascript before other code installed the event listeners that you want to track, then you could "replace" the addEventListener() method on the element(s) of interest with your own version that logged what event handlers were being set and then called the original addEventListener(). I consider this more of a "hacking" project for diagnosis or discovery than something one might use in a production web site.

Also for diagnosis, you can use debugging tools like the Chrome debugger to see event handlers that are attached to a given DOM object in the debugger. For example, in the Chrome debugger, if you right-click on an element in the page and select Inspect Element, it will open the Elements view of your page with the element you clicked on select. In the upper right corner of the window that opens, you can click on the "Event Listeners" tab and it will then list out each event that has a listener. If you expand a given event (like "click"), then you can see each click handler for that object.

Here's a screenshot from the event listeners tab in the Chrome debugger:

enter image description here

jfriend00
  • 683,504
  • 96
  • 985
  • 979