So I know that we can have multiple event handlers on the .on() method
$(document).on({ 'click': function (e) { // function }, 'hover': function (e) { // function } });
but is there anyway we can add multiple selectors to each event handler?
like this:
$(document).on('click', '#foo, .foo', function () { // function });
but with multiple .on() methods:
$(document).on({ 'click', '#foo': function (e) { // doesn't work :( }, 'hover', '.foo': function (e) { // doesn't work :( } });
Thanks in advance
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() { // ... } } });