1

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

4
  • 1
    that's not a valid object :) Commented Jan 17, 2017 at 10:23
  • so there isn't a way this can be done? Commented Jan 17, 2017 at 10:24
  • If you are having different selecters for each event, why not just split them out into their own on - it will be far more maintainable Commented Jan 17, 2017 at 10:24
  • use multiple on() methods or in case you need common selector then use selector as second argument Commented Jan 17, 2017 at 10:25

1 Answer 1

7

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() {
           // ...
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.