If I have multiple events on an element I am currently handling those events as written here:
$("body").on("click", ".element", function(e) {
// Do something on click
});
$("body").on("change", ".element", function(e) {
// Do something on change
});
Is there a way to combine all the events on an element in one on()
call? What is the best practice if there are multiple events associated with one element?
$("body").on("change click", ".element", function(e) {
// Can I detect here if it was change or click event and perform an action accordingly?
});
If I have multiple events on an element I am currently handling those events as written here:
$("body").on("click", ".element", function(e) {
// Do something on click
});
$("body").on("change", ".element", function(e) {
// Do something on change
});
Is there a way to combine all the events on an element in one on()
call? What is the best practice if there are multiple events associated with one element?
$("body").on("change click", ".element", function(e) {
// Can I detect here if it was change or click event and perform an action accordingly?
});
Share
Improve this question
edited Apr 22, 2015 at 18:29
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Apr 22, 2015 at 10:22
A PatelA Patel
2151 silver badge4 bronze badges
4
|
4 Answers
Reset to default 21You can use the type
property of the event to determine which logic to execute:
$('body').on('change click', '.element', function(e) {
if (e.type == 'click') {
// do something...
}
else if (e.type == 'change') {
// do something else...
}
});
Alternatively you can provide an object to on
which contains the functions to bind with the event type names as the keys:
$('body').on({
click: function() {
// do something on click...
},
change: function() {
// do something on change...
}
}, '.element');
Personally I would use the latter method. The whole point of having a unified on()
handler is negated when using a rather ugly if
statement to split the event types.
Yes! jQuery passes the event object which contain the event information:
$("body").on("change click", ".element", function(e) {
console.log(e.type);
});
You can use the event.type
. Some will say it's bad practice and others may find it useful.
$("body").on("change click", ".element", function(event) {
switch (event.type) {
case 'click':
break;
case 'change':
break;
default:
}
});
jQuery event.type
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="element" />
e.type
to figure out which event kind was triggered – user3154108 Commented Apr 22, 2015 at 10:25