Namespacing multiple events using jquery "on"

Satisfying which correct method for namespace contains multiple events using jquery "on" ...

, eg:

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

This does not work ... If I remove the ".namespace", it will work.

An example jquery on with a workspace namespace:

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

I understand that I can do mouseenter / mouseleave events seprately ... just curious if there is a way to pass namespaces through an object

Thanks!

+6
source share
3 answers

To connect to multiple events, you must pass a list of events separated by spaces:

 $(".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); } }); 

It seems like this is working, I can’t confirm this because I am not on my machine. Give it a try.

+4
source

The code "Below" is actually correct - I had a problem with a conflict with names earlier in the code.

 $(".parent-selector").on({ "mouseenter.namespace": function() { // mouseenter event }, "mouseleave.namespace": function() { // mouseleave event } }, ".selector"); 
+3
source

From what you said in the comment, you want to run another function for each namespace. It seems strange that you combine them to want to do something else. But if you want to know what caused the event, you can use event.type .

 $("#foo").on("mouseover mouseout", ".bar", function(evt){ console.log(evt.type); } ); 

Jsfiddle

0
source

All Articles