jQuery multiple events to trigger the same function
Solution 1:
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)
Solution 2:
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");
})
Solution 3:
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.