Reputation: 3222
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?
Upvotes: 4
Views: 1183
Reputation: 5690
you can do this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p class="foo" style="height: 30px;width: 40px;">Test</p>
<script>
$(".foo").on('mouseenter click mouseleave', function (event) {
alert('ok')
});
</script>
Upvotes: 1
Reputation: 2464
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>
Upvotes: 1
Reputation: 75327
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
Upvotes: 6