I have a function I'd like to do whenever either user clicks one of the anchor elements, such as this
$('.element').on('click', function(){
// do stuff here
});
and I want to do the same thing if a select element has changed its value, such as this
$('select').on('change', function(){
// do same stuff here
});
I know I could do
$('.element', 'select').on('click change', function(){
// do stuff here
});
but that would also trigger whenever I click on the select element and I don't want to confuse user and do something then, just when the select element value has changed.
The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.
In jQuery, we can add one or more than one event handler on any element easily.
jQuery - Multiple Elements SelectorYou can specify any number of selectors to combine into a single result.
JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });
You don't have to make your function inline.
var doStuff = function() {
// do stuff here
});
$('.element').on('click', doStuff);
$('select').on('change', doStuff);
One of the most readable ways to handle this is to create a separate function:
function doStuff(){
//do stuff here
}
$('.element').on('click', function(){
doStuff();
});
$('select').on('change', function(){
doStuff();
});
This also gives you a lovely opportunity to make it more clear what your code is for, by giving that function a nice, meaningful name.
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