lolbas lolbas - 3 months ago 12
jQuery Question

Bind click events for multiple classes with one call

On page load I am binding a lot of

click
events to different objects and code looks like this:

$(document).on('click', '.class1', function() { ... });
$(document).on('click', '.class2', function() { ... });
$(document).on('click', '.class3', function() { ... });
...


which I find to look pretty messy. I know that with jQuery one can bind multiple different events on one DOM element:

$(document).on({
click: function() { ... },
mouseenter: function() { ... },
mouseleave: function() { ... },
...
});


Can this be done in a similar way for multiple classes? Something like this:

$(document).on('click', {
'.class1': func1,
'.class2': func2,
'.class3': func3,
...
});


Please note, that
func1
,
func2
,
func3
, etc implement different logic and cannot be combined.

Answer

That syntax is not supported by jQuery. You can bind the event handlers by iterating through the object:

var handlers = {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
};

Object.keys(handlers).forEach(function(sel) {
    $(document).on('click', sel, handlers[sel]);
});

You can also define a utility function:

/**
 * A utility function for mass event delegation
 * @param  {String|Object} parent - the target of event delegation
 * @param  {String} event - event name
 * @param  {PlainObject} handlers
 * @return {undefined}
 */
$.delegate = function(parent, event, handlers) {
  parent = $(parent);
  Object.keys(handlers).forEach(function(sel) {
    parent.on(event, sel, handlers[sel]);
  });
}

$.delegate(document, 'click', {
  '.class1': function() { ... },
  '.class2': function() { ... },
  '.class3': function() { ... },
});