bsbak bsbak - 5 months ago 56
jQuery Question

jQuery register events in loop

How can i register "on" events in loop:

evetns = [
for(events...) {
$(document).on(events[i], 'someTarget', function() {...});

Answer Source

Don't register events in a for loop is my answer.

The on() function delegates the events on the same object, so there is no need for this kind of trickery. What you can do is to use events.join(' ').

This way the $(document) object gets all the events in a string separated by a single space resulting in:

$(document).on('click mouseover ...', function(){/**/});

Now the trick to optimize this, I'd say is use an eventHandler that maps specific functions to separate events.

$(document).on(events.join(' '), myEventHandler);

function myEventHandler(e){
    switch (e.type){
        case 'click': return myClickFn(e);
        case 'mouseover': return myOverFn(e);
        default: return false;

This way all functionality can be kept separate in the browser's memory.

Imagine without the switch statement, you can achieve all events to fire the same function at the same time the event occurred. If that is what you need however, I suggest to use throttle or debounce to handle this use-case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download