Is there a way to have keyup
, keypress
, blur
, and change
events call the same function in one line or do I have to do the
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
It sounds like what you actually want is something like this:
$('#ValidatedInput').keydown(function(evt) {
// If enter is pressed
if (evt.keyCode === 13) {
evt.preventDefault();
// If changes have been made to the input's value,
// blur() will result in a change event being fired.
this.blur();
}
});
$('#ValidatedInput').change(function(evt) {
var valueToValidate = this.value;
// Your validation callback/logic here.
});
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.
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)
This is how i do it.
$("input[name='title']").on({
"change keyup": function(e) {
var slug = $(this).val().split(" ").join("-").toLowerCase();
$("input[name='slug']").val(slug);
},
});
The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.
I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:
My workaround have been to first define the function,
function myFunction() {
...
}
and then handle the events individually
// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);
This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue
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.