I am upgrading a web project containing 2 views with plenty of elements.
At this time, all elements have several events like mouseenter, mouseleave, click, … which are defined one by one during the web page rendering.
My question is : is it more efficient to use the last jQuery method .on() using an events map and a dynamic selector like this :
$("#main-container").on({
mouseenter: function (event) {
//Do stuff
},
mouseleave: function (event) {
//Do stuff
},
mousedown: function (event) {
//Do stuff
}
},
".cartridge"
);
than the current events declarations:
$('[id^="cartridge"]').each(function(index) {
$(this).click(function(){
//Do stuff
});
$(this).mouseenter(function(){
//Do stuff
});
$(this).mouseleave(function(){
//Do stuff
});
});
According to the jquery API of .on() it is more efficient cause there’s only one event attached to your #main-container and the events coming from the different .cartridge just need to “bubble up” to this container.
From jquery API :
http://api.jquery.com/on/ see “Direct and delegated events”