0

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();
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Robin Maben
  • 22,194
  • 16
  • 64
  • 99
  • 2
    This question have a similar answer: http://stackoverflow.com/questions/5848598/how-all-events-of-dom-element-can-be-bind – Caio Alves Dec 28 '11 at 12:01
  • Thanks, somehow that didn't show up in the 'similar questions' sections when I was posting this. :) Anyways, my question says 'neat' I would still like to know if there are other ways to do this. – Robin Maben Dec 28 '11 at 12:13

2 Answers2

3

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 :)

abuduba
  • 4,986
  • 7
  • 26
  • 43
0
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

bragboy
  • 34,892
  • 30
  • 114
  • 171
MicroEyes
  • 3,680
  • 4
  • 26
  • 35