Demnogonis Demnogonis - 28 days ago 8
jQuery Question

Multiple event handlers on dynamic content with .on()

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?

Answer

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