Matías Cánepa
Matías Cánepa

Reputation: 5974

Get list of events attached to an element with jQuery

I want to retrieve a list of events attached to an element...

<div id="div_test">click HERE!</div>

This works

$("#div_test").click(function(e)
{
    var events_list = $._data( $(this)[0], 'events');
    console.log(events_list.click[0]);
});

But why this doesn't?

$(document).on("click", "#div_test", function(e)
{
    var events_list = $._data( $(this)[0], 'events');
    console.log(events_list.click[0]);
});

FIDDLE

Upvotes: 0

Views: 258

Answers (1)

Dekel
Dekel

Reputation: 62536

The reason for that is that the click event was not triggered on the #div_test element, but on the document element.
You can check e.delegateTarget for both versions to see which element triggered the click event:

$(document).on("click", "#div_test1", function(e) {
  console.log(e.delegateTarget.nodeName);
});

$("#div_test2").click(function(e) {
  console.log(e.delegateTarget.nodeName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_test1">click HERE!</div>
<br /><br />
<div id="div_test2">click HERE!</div>

When you use $("#div_test").click you attach the click event to that specific element, and this allows you to get all the events that were attached to that element.

However when you use $(document).on("click", "#div_test" You don't attach a click event to the #div_text element that exists inside your document.
What you actually do is you attach the click event to your document element, and while the browser catch that event, jquery checks if the actual element that you clicked on is the #div_test element.
This allows you to "attach event" to elements that are not even created, yet.

To sum it up:

$(document).on("click", "#div_test", function(...

IS NOT

$(document).find('#div_test').on("click", function(...

Upvotes: 1

Related Questions