Is there a neat way to bind an event handler to an element irrespective of event type?
For e.g., I need something like:
$('#elem').bind(function(e){
//do stuff for any event originating from this element
e.stopPropagation();
});
Is there a neat way to bind an event handler to an element irrespective of event type?
For e.g., I need something like:
$('#elem').bind(function(e){
//do stuff for any event originating from this element
e.stopPropagation();
});
You can change the default behavior of bind
method.
If we give a one argument which will function add this to all events
Check this out.
$.fn.init.prototype.bind = ( function( old ) {
return function( ) {
if( arguments.length == 1 && typeof arguments[0] === "function" ) {
// if we'll put to bind method one argument which is function
// list of whole of events - you set themselves as needed
return this.bind( "click keydown keyup keypress mouseover mouseenter mouseout mouseleave mousedown mouseup mousemove change blur focus scroll resize load unload beforeunload", arguments[0] );
} else {
// trigger original bind method
return old.apply( this, arguments )
} ;
}
})( $.fn.init.prototype.bind );
and now:
$( "body" ).bind( function() { console.log( this ) } );
Poof :)
var eventsList = "blur, focus, load, resize,
scroll, unload, beforeunload, click, dblclick,
mousedown, mouseup, mousemove, mouseover, mouseout,
mouseenter, mouseleave, change, select, submit, keydown,
keypress, keyup, error";
(/* selector of user choice */).bind(eventsList, function(){
//All operations here..
});
You can find list of events here... JQuery Events