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.
Right-click the element. In the context menu, Click 'Inspect Element' If there is an 'ev' icon next to the element (yellow box), click on 'ev' icon. Displays all events for that element and event handler.
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.
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.
$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding. Traditional method: document.
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');
}
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() );
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With