jQuery multiple events to trigger the same function
You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});
Another option is to use chaining support of jquery api.
As of jQuery 1.7, the .on()
method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind()
method is used for attaching an event handler directly to elements.
$(document).on('mouseover mouseout',".brand", function () {
$(".star").toggleClass("hovered");
})
You can use .on()
to bind a function to multiple events:
$('#element').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
});
Or just pass the function as the parameter to normal event functions:
var myFunction = function() {
...
}
$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)
.change(myFunction)
I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.
So, for those interested, event.type
is my answer :
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
More info in the jQuery doc.