Yosef Yosef - 6 months ago 9
Javascript Question

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);
});

Answer

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 */
});