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!
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.
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 .
You can assign as many handlers as you want to an event using addEventListener().
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With