Rafael Herscovici
Rafael Herscovici

Reputation: 17134

applying the same .click event to two different divs

i have two different divs (code was simplified, this is not the actual code.)

<div id="test"></div>
<div id="funt"></div>

what i want is, to attach the same click event to #funt: something like:

$('#test').click(function() {
    DoWork();
});
$('#funt).click(function() {
    DoWork();
});

function DoWork(){
    alert('yes');
}

but isn't there a way to define multiple div's the same click event?

lets say ( yes, i know this does not work! )

($('#test'),('#funt')).click(function(){alert('yes')});

Upvotes: 7

Views: 15301

Answers (6)

Ajay Gupta
Ajay Gupta

Reputation: 2957

You can try this syntax to do so,

When working with Classes

$(".className1, .className2, .classNameN").on('click', function(){
    Do_Some_Work();
});

When working with Id's

$("#ID1, #ID2, #IDN").on('click', function(){
    Do_Some_Work();
});

When working with Combination of ID and Class

<div id="z">z
    <div class="w">w</div>
    <div class="x">x</div>
   <div class="y">y</div>
</div>

$('#z.w , #z.y').on('click', function(){
    Do_Some_Work();
    //Pointer come here only when it click on `W` and `Y`
});

Upvotes: 0

ysrb
ysrb

Reputation: 6740

This should work

($('#test','#funt')).click(function(){alert('yes')});

http://api.jquery.com/multiple-selector/

Upvotes: 0

Fed44
Fed44

Reputation: 194

You have two options, either you could give both of those divs a class and then just run the code:

$(".myclass").click(function() {
    DoWork();
});

Or you could define a function like:

function hookClick(arr, handler)  {
    foreach (var i in arr) {
        $(i).click(handler);
    }
}

then run it using

hookClick(["#div1", "#div2"], function() { /*do sth cool })

Upvotes: 0

vcsjones
vcsjones

Reputation: 141688

You were actually pretty close:

 $('#test, #funt').click(function() {
      });

Upvotes: 0

James Hill
James Hill

Reputation: 61872

Assign a class to your div's, and then assign the click event using the class like this:

<div class="clickable" id="test"></div>
<div class="clickable" id="funt"></div>

Then

$('.clickable').click(function()
{
    DoWork();
});

You could also list the id's like this:

$("#test, #funt").click(DoWork);

I usually try to use classes because it's cleaner when you're dealing with multiple divs - you don't have to list the ID of each.

Upvotes: 0

karim79
karim79

Reputation: 342765

Simply:

$("#test, #funt").click(DoWork);

See Multiple Selector.

Upvotes: 20

Related Questions