Search code examples
javascriptjquery

Get all events handlers attached to an element


I need to find all events handlers attached to #mySelect and if the event is created via jQuery I can get it , here alert(e) will show only "change" without "click"

JavaScript :

$("#mySelect").change(function(){
    alert("changed");
})           
$.each($._data(  $("#mySelect")[0], "events" ), function(e) {
    alert(e);
})

Html :

<select id="mySelect" onclick="alert('hello')" >
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
</select>

Solution

  • The short answer is that it's not possible to reliably determine all the listeners on an element just using javascript.

    The long answer is that there is no standard mechanism to list all attached listeners. Some libraries keep a list of listeners that have been attached using the library, but don't necessarily know about other listeners. Listeners added in the markup or as element properties can be found by testing related element properties and attributes (somewhat tedious testing for onclick, onchange, onblur, etc. for each element). But it's impossible to find a listener added using addEventListener or attachEvent unless a reference has been kept somewhere and it's made available (see comment about libraries).

    Also, there are "delegated" listeners that give the appearance of being attached to an element when in fact they are attached to a parent element.