Search code examples
javascriptjqueryperformancejquery-chaining

Multiple chained .on('click') event listeners in jQuery


I have several click handlers on a carousel plugin (GitHub repo here).

When I initially coded it, I forgot about jQuery chaining:

$gallop.on("click", ".advance",  function(){ [snip 1] })
$gallop.on("click", ".retreat",  function(){ [snip 2] })
$gallop.on("click", ".autoplay", function(){ [snip 3] })
$gallop.on("click", ".picker",   function(){ [snip 4] });

They're all on the same .gallop element, so I am able to improve the code by chaining them together:

$gallop
    .on("click", ".advance",  function(){ [snip 1] })
    .on("click", ".retreat",  function(){ [snip 2] })
    .on("click", ".autoplay", function(){ [snip 3] })
    .on("click", ".picker",   function(){ [snip 4] });

They're also all listening for the click event: only the selectors are different for each handler. Is there a way to put multiple selector/handler items in the same .on() method? Something like this?

$gallop
    .on("click", 
        ".advance",  function(){ [snip 1] },
        ".retreat",  function(){ [snip 2] },
        ".autoplay", function(){ [snip 3] },
        ".picker",   function(){ [snip 4] });

Solution

  • There is no built-in way of specifying multiple separate pairs of selector/handler in one .on() call.

    If you want different event handling functions for each of the different selectors, then your second option is probably the cleanest way to do it.

    You could make one giant event handler and then branch based on the target (but unless you have a bunch of common code among all the handlers, this is probably not the cleanest way to do it):

    $gallop.on("click", ".advance, .retreat, .autoplay, .picker", function(e) {
        // look at the class on e.target and decide what to do
    })