How can I bind all events on a DOM element?
How can I bind all events (i.e. click
, keypress
, mousedown
) on a DOM element, using jQuery, without listing each one out individually?
Example:
$('#some-el').bind('all events', function(e) {
console.log(e.type);
});
Solution 1:
there is a simple (but not accurate) way to test all events:
function getAllEvents(element) {
var result = [];
for (var key in element) {
if (key.indexOf('on') === 0) {
result.push(key.slice(2));
}
}
return result.join(' ');
}
then bind all events like this:
var el = $('#some-el');
el.bind(getAllEvents(el[0]), function(e) {
/* insert your code */
});
Solution 2:
You also can redefine jQuery.event.trigger to catch each event, but, I think, this way is good only for exploring external API, not for production:
var oldJQueryEventTrigger = jQuery.event.trigger;
jQuery.event.trigger = function( event, data, elem, onlyHandlers ) {
console.log( event, data, elem, onlyHandlers );
oldJQueryEventTrigger( event, data, elem, onlyHandlers );
}