I have 3 buttons inside one div and I want to add the same click listener to all of them. I have a few actions on those buttons so I first keep them as variables in the begging of the function and then I want to add the on listener, using those variables. Is there any way? The HTML looks like this:
<div class="wrapper">
<button class="a"></button>
<button class="b"></button>
<button class="c"></button>
</div>
The JS:
var $wrapper = $('.wrapper'),
$aBtn = $wrapper.find('.a'),
$bBtn = $wrapper.find('.b'),
$cBtn = $wrapper.find('.c');
//The working but less neat solution
$('.wrapper .a, .wrapper .b, .wrapper .c').on('click', func);
//What I want
($aBtn, $bBtn, $cBtn).on('click', func);
You can use .add() // Ref link
var $wrapper = $('.wrapper'),
$aBtn = $wrapper.find('.a'),
$bBtn = $wrapper.find('.b'),
$cBtn = $wrapper.find('.c');
//What I want
$($aBtn).add($bBtn).add($cBtn).on('click', func);
function func(){alert($(this).attr("class"))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<button class="a">a</button>
<button class="b">b</button>
<button class="c">c</button>
</div>
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