Is there a way to check if an event exists in jQuery? I’m working on a plugin that uses custom namespaced events, and would like to be able to check if the event is bound to an element or not.
This question is related to
javascript
jquery
jquery-events
eventtrigger
Below code will provide you with all the click events on given selector:
jQuery(selector).data('events').click
You can iterate over it using each or for ex. check the length for validation like:
jQuery(selector).data('events').click.length
Thought it would help someone. :)
I wrote a plugin called hasEventListener which exactly does that.
Hope this helps.
You may use:
$("#foo").unbind('click');
to make sure all click events are unbinded, then attach your event
This work for me it is showing the objects and type of event which has occurred.
var foo = $._data( $('body').get(0), 'events' );
$.each( foo, function(i,o) {
console.log(i); // guide of the event
console.log(o); // the function definition of the event handler
});
use jquery event filter
you can use it like this
$("a:Event(click)")
To check for events on an element:
var events = $._data(element, "events")
Note that this will only work with direct event handlers, if you are using $(document).on("event-name", "jq-selector", function() { //logic }), you will want to see the getEvents function at the bottom of this answer
For example:
var events = $._data(document.getElementById("myElemId"), "events")
or
var events = $._data($("#myElemId")[0], "events")
Full Example:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#textDiv").click(function() {
//Event Handling
});
var events = $._data(document.getElementById('textDiv'), "events");
var hasEvents = (events != null);
});
</script>
</head>
<body>
<div id="textDiv">Text</div>
</body>
</html>
A more complete way to check, that includes dynamic listeners, installed with $(document).on
function getEvents(element) {
var elemEvents = $._data(element, "events");
var allDocEvnts = $._data(document, "events");
for(var evntType in allDocEvnts) {
if(allDocEvnts.hasOwnProperty(evntType)) {
var evts = allDocEvnts[evntType];
for(var i = 0; i < evts.length; i++) {
if($(element).is(evts[i].selector)) {
if(elemEvents == null) {
elemEvents = {};
}
if(!elemEvents.hasOwnProperty(evntType)) {
elemEvents[evntType] = [];
}
elemEvents[evntType].push(evts[i]);
}
}
}
}
return elemEvents;
}
Example usage:
getEvents($('#myElemId')[0])
I ended up doing this
typeof ($('#mySelector').data('events').click) == "object"
Source: Stackoverflow.com