Namespacing multiple events using jquery "on"

javascript, jquery

Solution

To attach to multiple events you have to pass a space separated list of events:

$(".parent-selector").on("mouseenter.namespace mouseleave.namespace",
                         ".selector", function() { });

Edit:

You can always get the type of event inside the callback and call other functions inside:

$(".parent-selector").on("mouseenter.namespace mouseleave.namespace", ".selector", function(e) {
    if (e.type == "mouseenter.namespace") {
        myMouseEnter(e);
    } else if (e.type == "mouseleave.namespace") {
        myMouseLeave(e);
    }
});

Althrough it seems to work, I can't confirm that, cause I'm not on my machine. Give it a try.

Problem

Wondering what the correct method to namespace multiple events using jquery "on" ... for example: ``` $(".parent-selector").on({ "mouseenter.namespace": function() { // mouseenter event }, "mouseleave.namespace": function() { // mouseleave event } }, ".selector"); ``` This is not working... If i remove the ".namespace" it does work. Example of jquery on with working namespace: ``` $(".parent-selector").on("mouseenter.namespace", ".selector", function() { }); ``` I understand I can do both the mouseenter/mouseleave events seprately ... just curious if there is a way to pass namespaces through the object Thanks!

Original source