How can I bind all events on a DOM element?

Yosef picture Yosef · May 1, 2011 · Viewed 56.7k times · Source

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

otakustay picture otakustay · May 1, 2011

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