We can attach multiple events to an element using .on()
$('.foo').on({
'click':function(e){
// do stuff
},
'mouseenter':function(e){
// do some other stuff
},
'mouseleave':function(e){
// do completely different stuff
}
});
We can also attach a handler to the document and filter for our elements to have the event on subsequently created elements
$(document).on('click', '.foo', function(e){
// do stuff
});
Is it possible to combine these behaviours to bind multiple events to an element and future elements?
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
You can try like this
$(document).on({
click: function() {
alert("click")
},
mouseenter: function() {
alert("mouseenter")
},
mouseleave: function() {
alert("mouseleave")
}
}, ".foo");
<div class="foo">test</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
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