Assigning more than one class for one event
class, events, jquery
Solution
Approach #1
function doSomething(){
if ($(this).hasClass('clickedTag')){
// code here
}
else {
// and here
}
}
$('.tag1').click(doSomething);
$('.tag2').click(doSomething);
// or, simplifying further
$(".tag1, .tag2").click(doSomething);
Approach #2
This will also work:
$(".tag1, .tag2").click(function(){
alert("clicked");
});
Fiddle
I prefer a separate function (approach #1) if there is a chance that logic will be reused.
See also How can I select an element with multiple classes? for handling multiple classes on the same item.
Problem
I have an click event that I want to assign to more than class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places. What I want is something like $('.tag' '.tag2'), which of course don't work. ``` $('.tag').click(function (){ if ($(this).hasClass('clickedTag')){ // code here } else { // and here } }); ```