Multiple click events on one element

http://jsfiddle.net/rHVcX/1/

Is it possible to have multiple click events on one elements, when using different selectors?

<button id="test" class="testclass">test</button>
<button id="test2" class="testclass2">test 2</button>

//only B
$('.testclass')[0].click(function(){alert('A');});
$('#test').click(function(){alert('B');});

// A and B
$('#test2').click(function(){alert('A2');});
$('#test2').click(function(){alert('B2');});

Upvotes: 2

Views: 4067

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23142

It is possible.

However, this line:

$('.testclass')[0].click(function(){alert('A');});

Will not work. It should be:

$('.testclass').eq(0).click(function(){alert('A');});

Indexing the jQuery object will give you the DOM element at index zero, not a filtered jQuery object.

http://api.jquery.com/eq

Upvotes: 1

genesis
genesis

Reputation: 50982

remove [0] or change it to .eq(0)

<button id="test" class="testclass">test</button>
<button id="test2" class="testclass2">test 2</button>

//only B
$('.testclass').click(function(){alert('A');});
$('#test').click(function(){alert('B');});

// A and B
$('#test2').click(function(){alert('A2');});
$('#test2').click(function(){alert('B2');});

working fiddle

http://jsfiddle.net/rHVcX/2/

Upvotes: 0

Mrchief
Mrchief

Reputation: 76258

Yes you can have multiple click events on the object. The handlers wil be called in the order they were added (unless you say return false in one of them).

Upvotes: 0

SLaks
SLaks

Reputation: 888203

Yes, that's perfectly possible.

However, you're misusing jQuery.
Writing $(...)[0] gives you the first raw DOM element in the set.
It isn't a jQuery object, so you can't call jQuery's click method on it.

Instead, you should call the eq method, which returns a jQuery object containing a single element from the original set.

Change it to $('.testclass').eq(0).click(...)

Upvotes: 4

Related Questions