0

I wonder how can I get the list of event listeners for some event?

Suppose I add the event listener to window with this code:

window.addEventListener('click', 
    function() { 
        console.log(111); 
        // a lot of code ...
    }, false)

But if I am about to see these listeners with window.onclick it returns null. However when I click on the window this event handler fires. Can I see this list with another ways?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Itsme
  • 11
  • 1
  • 2
  • 1
    not what you are looking for exactly, but in google chrome, when you select element, on the right side of the developer window there's tab with that show all event's that this element is subscribed for. And since the events are bubbling I'm not sure if what you are asking is relevent. Would be interesting someone to say exactly. – Leron Oct 03 '14 at 09:50

1 Answers1

0
    1. elem.onclick property and elem.addEventListener('click') do not depend on each other, but the order of attaching listeners really matters

<body>
  <span> body stuff </span>
  <script>
    var element = document.body
    element.addEventListener('click', function(){ console.log(1) })
    element.onclick  = function(){ console.log(2) }
    element.addEventListener('click', function(){ console.log(3) })
  </script>
</body>

do click on body and get '1 2 3'

then set element.onclick = null

do click on body and get '1 3'

  • 2.1. the property onclick (which can be assigned to only one listener that is a function, not an array) is available from the script for each element (like any other property)

  • 2.2. There is definetely no way to see the event listeners added with addEventListener from the script, however browser integrated debugger will show their state on any breakpoint (or in any given moment).

    In Chrome 32+:

    F12 -> Pick 'Elements' (Tab) -> Choose <body> element -> On the right pick 'EventListeners'

    In other browsers you may need an extension (Dragonfly, Firebug etc.)

  • 2.3. Chrome debugger will show all eventListeners (sorted by event name) for current element and its parents up to the document. But I do not know if it is possible to see the window event listeners.

    1. If you use jQuery, there is a way to get from script a bunch of listeners added only by jQuery, though it's a different story.
diziaq
  • 6,881
  • 16
  • 54
  • 96