ekclone
ekclone

Reputation: 1092

jQuery .on() method with multiple event handlers & multiple selectors

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

Upvotes: 1

Views: 5024

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

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() {
           // ...
        }
    }
});

Upvotes: 7

Related Questions