Keith
Keith

Reputation: 4147

Using multiple variables in an expression

Say I have:

var varOne = $('#varOne'),
varTwo = $('#varTwo'),
varThree = $('#varThree');

How do I use all three or two in one line like:

(varOne, varTwo, varThree).on('click', function(){
   // code here
})

Upvotes: 1

Views: 52

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Attach your event-handler to multiple selectors at-a-time

$("#varOne, #varTwo, #varThree").on('click', function(){
  // code here
});

Working Example:-

$(document).ready(function(){
  var varOne = $('#varOne');
  varTwo = $('#varTwo');
  varThree = $('#varThree');
  $("#varOne, #varTwo, #varThree").on('click', function(){
    console.log($(this).html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="varOne">div1</div>
<div id="varTwo">div2</div>
<div id="varThree">div3</div>

Upvotes: 3

TJBlackman
TJBlackman

Reputation: 2313

You should use DELEGATION.

If your 3 selectors share a parent, you can add the event listener to that parent ONE TIME and ask i to listen for any of those three elements.

$.on('click','put, selectors, here', function(){ ... })

https://jsfiddle.net/sq8v5twL

http://api.jquery.com/on/

Upvotes: 0

Racil Hilan
Racil Hilan

Reputation: 25351

Convert your anonymous function to a named one and call it from the three events:

varOne.on('click', myClickEvent);
varTwo.on('click', myClickEvent);
varThree.on('click', myClickEvent);

function myClickEvent() {
    // code here
}

Alternatively, if you're only using your variables for the sake of creating the event, then you don't need them and you can use the IDs directly:

$("#varOne", "#varTwo", "#varThree").on('click', function(){
    // code here
});

Notice the semicolon at the end. Although optional, it is strongly recommended to use semicolons appropriately.

Upvotes: 3

Andreas
Andreas

Reputation: 21881

$.add():

Create a new jQuery object with elements added to the set of matched elements.


var combinedElements = varOne.add(varTwo).add(varThree);

combinedElements.on("click", function() {

});

Or

var combinedElements = $.fn.add.call(varOne, varTwo, varThree);

combinedElements.on("click", function() {

});

Example:

var varOne = $("#varOne"),
    varTwo = $("#varTwo"),
    varThree = $("#varThree"),
    combinedElements = varOne.add(varTwo).add(varThree);

combinedElements.on('click', function(){
  console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="varOne">div1</div>
<div id="varTwo">div2</div>
<div id="varThree">div3</div>

Upvotes: 3

Related Questions