How can I trigger the same function from multiple events with jQuery?
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)
jQuery .on() method with multiple event handlers & multiple selectors
If you want different matching elements on different events, you need to use different on
calls. You can use a single on
call to hook multiple events for the same elements, but you can't use a single on
for a mix and match of events and selectors (nor is there any need to).
You could, of course, create your own function that does that. For instance, something vaguely like:
$.fn.mixon = function(events) {
Object.keys(events).forEach(function(selector) {
var entry = events[selector];
Object.keys(entry).forEach(function(event) {
this.on(event, selector, entry[event]);
}, this);
}, this);
return this;
};
...which you could use like this:
$(document).mixon({
"#foo": {
"click focus": function() {
// ...
}
},
".foo": {
click: function() {
// ...
}
}
});
JQuery .on() method with multiple event handlers to one selector
That's the other way around. You should write:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
click: function() {
// Handle click...
}
}, "td");
Same selector with multiple functions/event handlers
Options:
Use chaining as already suggested
$('.icMenu span.menu').each(function() {
// do something
}).click(function() {
// do something else
});
Or simply use a local variable to avoid running the jQuery selector twice:
var $menus = $('.icMenu span.menu');
$menus.each(function() {
// do something
});
$menus.click(function() {
// do something else
});
Basic rule:
The key is to always avoid running the selector more than once as that has a large overhead.
Delegated Events:
If your elements are ever dynamically created, you would move the click
to a delegated on event handler anyway, so your question would become a non-issue (they would be the same selector, but separated in time):
$(document).on('click', '.icMenu span.menu', function(){
// Do something on dynamically created elements
});
In a delegated event handler, the selector is only run after the event is caught on an ancestor (in this case document
). The function is then applied to any matching elements that caused the event.
Attaching multiple events to multiple elements for a single handler on the go in jquery
I don't think there is any smart shortcut you can use here. The best I can think of is to extract functionality into separate function and pass it as event handler for both onclick
and onchange
:
function action() {
$('#myTable1').append('<tr><td> one<td><td> two </td> </tr>');
}
$("#accountType").on('change', action);
$('#buttonId').on('click', action);
Demo: http://jsfiddle.net/Lv08z60m/
using .off function for multiple event handlers on a single selector
You can just seperate the events by spaces, see the 2nd description of the .off function here: http://api.jquery.com/off
$(document).off("mouseenter mouseleave click",".handle");
Multiple event handlers on dynamic content with .on()
Yes;
$(document).on({
'click':function(e){
// do stuff
},
'mouseenter':function(e){
// do some other stuff
},
'mouseleave':function(e){
// do completely different stuff
}
}, '.foo');
https://jsfiddle.net/ktybjprh/
This is covered by the .on( events [, selector ] [, data ] )
signature, available as of jQuery 1.7
jQuery - Multiple events to trigger same function but with different elements
Use more than one line:
$('#element').on('submit',function() { load_product_serial(); });
$('#element2').on('keypress blur change',function() { load_product_serial(); });
Also, FYI, don't use the click
event to bind a function to a submit button click when what you really want to do is bind it to the submit
event of the form itself.
EDIT
Regarding the comment below about the event not defined
error, don't forget to pass in your event object as an argument:
function load_product_serial(event) {
....
event.preventDefault();
....
}
$('#element').on('submit',function(e) { load_product_serial(e); });
$('#element2').on('keypress blur change',function(e) { load_product_serial(e); });
jQuery's One - Fire once with multiple event types
Instead of using .one
, use .on
and remove the binding manually with .off
.
$('input').on('mouseup keyup', function(e){
console.log(e.type);
$(this).off('mouseup keyup');
});
Fiddle: http://jsfiddle.net/23H7J/3/
This can be done a little more elegantly with namespaces:
$('input').on('mouseup.foo keyup.foo', function(e){
console.log(e.type);
$(this).off('.foo');
});
This allows us to use a single identifier (foo) to remove any number of bindings, and we won't affect any other mouseup or keyup bindings the element may have.
Fiddle: http://jsfiddle.net/23H7J/41/
jQuery: Best way to handle multiple events for best performance
You must distinguish between binding events (attaching a callback to an event), and between actually processing the triggered events (calling/executing the callback). The first might occur only once per page, while the later might occur hundred of times depending on the user activity.
If you consider the event-binding only – which occurs on document ready (eventually) and each time the DOM changes (e.g. on Ajax Complete) – then using only one
.on()
call with only one callback is faster: http://jsperf.com/multiple-jquery-events/2If you consider the processing of the events being triggered – (i.e. the user clicks or mouse-overs
.myElement
) – then combining all events into one callback and differentiating them withif
statements is also faster than having multiple callbacks: http://jsperf.com/multiple-jquery-events/4
Here are some combined results from both tests:
The fastest to bind and also the fastest to process events:
$('#main').on('mouseenter mouseleave click', '.myElement', function(event) {
// Processing of the triggered event:
if (event.type == 'click') {
return false;
} else if (event.type == 'mouseenter') {
$(this).addClass('active');
} else if (event.type == 'mouseleave') {
$(this).removeClass('active');
}
});
The above code is the recommended syntax. The following examples are for information only.
About 30% slower to bind, and 50% slower to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
});
$('#main').on('mouseenter', '.myElement', function(event) {
$(this).addClass('active');
});
$('#main').on('mouseleave', '.myElement', function(event) {
$(this).removeClass('active');
});
The slowest to bind, and 70% slower to process the events:
$('#main').on({
mouseenter: function() {
$(this).addClass('active');
},
mouseleave: function() {
$(this).removeClass('active');
},
click: function() {
return false;
}
}, '.myElement');
About 25% slower to bind, and the slowest to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
});
$('#main').on('hover', '.myElement', function(event) {
$(this).addClass('active');
}, function() {
$(this).removeClass('active');
});
About 20% slower to bind, and 60% slower to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
}).on('mouseenter', '.myElement', function(event) {
$(this).addClass('active');
}).on('mouseleave', '.myElement', function(event) {
$(this).removeClass('active');
});
Related Topics
Javascript: Simple Way to Check If Variable Is Equal to One of Two or More Values
How to Access 'Window' (Target Page) Objects When @Grant Values Are Set
What Does Arrow Function '() => {}' Mean in JavaScript
Firebase -> Date Order Reverse
Dc.Js - How to Create a Row Chart from Multiple Columns
How to Overcome the Cors Issue in Reactjs
Why the Function Called by Settimeout Has No Callstack Limit
Three.Js:2Xmeshes Using Same Vector as Position
How to Check If an Object Has a Key in JavaScript
What Does the Function Then() Mean in JavaScript
How to Reload or Re-Render the Entire Page Using Angularjs
How to Consume Http Component Efficiently in a Service in Angular 2 Beta
Eslint Parsing Error: Unexpected Token
What Is This Practice Called in JavaScript
Using Chrome, How to Find to Which Events Are Bound to an Element