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
You could define the function that you would like to reuse as below:
var foo = function() {...}
And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:
$('#selector').on('keyup keypress blur change paste cut', foo);
Is there a way to have
keyup
,keypress
,blur
, andchange
events call the same function in one line?
It's possible using .on()
, which accepts the following structure: .on( events [, selector ] [, data ], handler )
, so you can pass multiple events to this method. In your case it should look like this:
$('#target').on('keyup keypress blur change', function(e) {
// "e" is an event, you can detect the type of event using "e.type"
});
And here is the live example:
$('#target').on('keyup keypress blur change', function(e) {
console.log(`"${e.type.toUpperCase()}" event happened`)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="target">
$("element").on("event1 event2 event..n", function() {
//execution
});
This tutorial is about handling multiple events.
It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:
function validate() {
// ...
}
const element = document.querySelector('#element');
['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
element.addEventListener(eventName, validate);
});
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");
})