8

I have some elements with a function bound to the click event. I want to bind that same function instead to the mouseover and mouseout events. Is it possible to get a reference to the click event so that I can assign it to those other events? I'm imagining something like this (inside each()):

$(this).bind('mouseover', $(this).click());
$(this).bind('mouseout', $(this).click());
$(this).unbind('click');

Questions You Might Ask

Why don't you just change the code that's binding it to the click event?

The JS that's setting this up is part of a Drupal module (DHTML Menu, if you're curious), so I don't want to change the module code because it will be wiped out when the module is inevitably updated in the future. I'm also using the click handler for other parts of the page - I only want to move it to mouseover and mouseout for one menu.

Brock Boland
  • 15,870
  • 11
  • 35
  • 36
  • 1
    Similar to http://stackoverflow.com/questions/516265/jquery-unbind-event-handlers-to-bind-them-again-later . –  Feb 08 '10 at 18:14

2 Answers2

13

In jQuery, all the events bound by jQuery are stored in data under the key events. The following would do what you want:

var $this = $(this),
    events = $this.data('events');
if( events && events['click'] ){
  // Loop through each click event bound to this control
  $.each( events['click'], function(){
   // this = the function
   $this.bind('mouseover mouseout', this);
  });
  // Finally, remove all `click` handlers with one call
  $this.unbind('click');
}
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • 9
    Just for other's future reference, this has been dropped in jquery 1.8. .data('events') isn't available. – Sam Greenhalgh Aug 20 '12 at 03:35
  • 8
    in jquery 1.8, you can still access the events dictionary with `$._data(element, "events")`, but that may change at any time. – hughes Aug 20 '12 at 17:41
  • What if I want to find all the events bound not only by jQuery but other methods/process also. – soham Aug 13 '13 at 14:02
3

Try this:

jQuery('#element').data('events');

You can also do this:

jQuery.each(jQuery('#element').data('events'), function(i, event){
    jQuery.each(event, function(i, eventHandler){
        console.log("The handler is " + eventHandler.toString() );
    });
});
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295