Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Can I use variables somehow with .on Jquery

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);
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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>

about 4 years ago · Santiago Trujillo Report

0

Using add function

$aBtn.add($bBtn,$cBtn).on('click', func);
about 4 years ago · Santiago Trujillo Report

0

The following code doesn't use variables, but you can sometimes simply bind events on selectors that wraps multiple elements

$('.wrapper button').on('click', func);

With this code, each button has an event handler attached to it. When you click an element, this reference the element like showcased in this jsfiddle : https://jsfiddle.net/3uwx15vg/1/

As an alternative to variables, you can even chain event handlers

$('.wrapper button').on('click', func).on('blur', func);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!