Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind an event handler to multiple elements jQuery?

Tags:

I've done some experimenting, but can't seem to successfully bind one event handler to multiple elements using jQuery. Here's what I've tried:

$('selector1', 'selector2').bind('click', function() {         $('someSelector').removeClass('coolClass');  }); 

I've tested all my selectors, and they are all valid.

Is what I'm trying to do even possible? If so, can I do it with .live() as well?

Thanks!

like image 272
Alex Avatar asked May 08 '10 05:05

Alex


People also ask

Can I add an event listener to multiple elements in JavaScript?

Adding an Event Listener to Multiple Elements Using a for...of Loop + IIFE. Open the console and click any of the buttons. The same event listener is added to each button using a for...of loop along with an immediately invoked function that passes the current element of the loop back into the function.

How do we bind events to elements using jQuery?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs. For more flexible event binding, see the discussion of event delegation in .

Can an event have multiple handlers?

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


1 Answers

To clarify let us extract the selector string into a variable:

var selector = ['selector1', 'selector2']; 

the above is similar to what you have written.

var selector = 'selector1, selector2'; 

this is the correct way to use the interface. Note that it is a comma separated list of selector in a single string.

$('selector1, selector2').bind(...) 
like image 102
Gabriel Avatar answered Nov 24 '22 07:11

Gabriel