Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine / Chain Multiple jQuery Object

Tags:

jquery

var $obj1 = $('a#one');
var $obj2 = $('a#two');
var $obj3 = $('a#three');

// Assume $('a#one, a#two, a#three') wasn't an option.

How do I assign one (same) event handler e.g. click() to those three jQuery objects? Essentially, I am looking for a more efficient way of doing:

$obj1.click(function() { /* Code A */ });
$obj2.click(function() { /* Code A */ });
$obj3.click(function() { /* Code A */ });
like image 955
moey Avatar asked Mar 16 '12 07:03

moey


2 Answers

Only (very) marginally shorter, but:

$([$obj1, $obj2, $obj3]).click(function() { });

You would want to define your handler outside of the first anonymous function though, so you'd really probably be better off with Jonas H's method. Just throwing another suggestion out there.

Note: you could technically do a hybrid, but it's quite lengthy:

var f = function() { };
$([$obj1, $obj2, $obj3]).click(f);

Really this question is only useful if you want to avoid the $a.click(f) over and over again, which is truly a better option than this jQuery abuse. :)

like image 200
Corbin Avatar answered Sep 19 '22 04:09

Corbin


Hmm, there's always .add(), but personally I prefer writing out the .click() functions one by one, if I started out with seperate variables anyway. No need to acquire additional overhead creating new jQuery objects for such trivial functionality.

$obj1.add($obj2).add($obj3).on('click' , function () { } );
// not sure if $obj1.add($obj2, $obj3) will work as well
like image 38
Richard Neil Ilagan Avatar answered Sep 20 '22 04:09

Richard Neil Ilagan