Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); }); 
like image 207
Ben Avatar asked May 01 '11 13:05

Ben


People also ask

What method can you use to bind an event to an element?

jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

How do you bind an event?

To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right.

Which method is used to bind a callback method for an event for DOM elements added at runtime?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event. Save this answer.

Which jQuery keyword should be used to bind an event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.


1 Answers

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 */ }); 
like image 69
otakustay Avatar answered Sep 19 '22 16:09

otakustay