Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all events handlers attached to an element

Tags:

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> 
like image 374
Mohamed Omezzine Avatar asked Aug 08 '13 00:08

Mohamed Omezzine


People also ask

How do you get all event listeners on an element?

Basically, 2 ways when defining events, just need to add the prefix on using the event attribute : element. addEventListener('click', function() {…}); element. onclick = function() {…}; element.

Which method attaches an event handler to an element?

The mouseleave() method attaches an event handler function to an HTML element.

Which methods helps us to attach one or more event handlers to a selected element?

The hover() Method The jQuery hover() method attach one or two event handler functions to the selected elements that is executed when the mouse pointer enters and leaves the elements.


1 Answers

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.

like image 155
RobG Avatar answered Sep 27 '22 19:09

RobG