Multiple triggers for a jquery-click-event

Viewed 1408

Sorry for that simple question, but how do I add multiple triggers to a jquery-click-event?

I tried that one here

$("#trigger1","#trigger2").click(function() {
    //something
});

But that doesn't work. What is the correct syntax there?

3 Answers

Should be like :

$("#trigger1, #trigger2").click(function() {
    //Put your logic here
});

Just remove the extra quotes.

Hope this helps.

The reason why your code is not working is you are using a context selector. So what it is saying is: Find #trigger2 and inside of that look for #trigger1.

But what you want is to use a multiple selector.

$("#trigger1, #trigger2").click( ... )

Or I would just use a common class so you do not have to keep track of the ids

$(".commonClass").click( ... )

Or something like

$(document).on("click", "#trigger1, #trigger2, #trigger3", function () {
    //do stuff
});

This will let you add as many listeners as you want on multiple DOM elements

Related