Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind an event handler to multiple element variables in jQuery?

I want to bind multiple elements that are defined as a variable. I know this is possible:

$('selector1, selector2').bind(...)

But I want to do something like this:

$($element1, $element2, $element3).bind(...)

Any ideas?

like image 264
kaleazy Avatar asked Jul 06 '13 01:07

kaleazy


People also ask

How do you apply an event listener to multiple elements?

Adding event listener to multiple elements To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.

Can an event have multiple handlers?

You can assign as many handlers as you want to an event using addEventListener().


1 Answers

You have to add them to one result set:

$element1.add($element2).add($element3).bind(...)

Or for an arbitrary number of elements:

var elems = [$element1, $element2, $element3, ...];
var $result = $();

$.each(elems, function() {
    $result = $result.add(this);
});

$result.bind(...);

Or with Array.reduce:

[$element1, $element2, $element3, ...].reduce(function($result, $elem) {
    return $result.add($elem);
}, $()).bind(...);
like image 151
Blender Avatar answered Oct 20 '22 00:10

Blender