Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 2 classes for the same function with jQuery

How do I run the same click function for 2 classes ?

I have this :

$('.buythis').click(function(){ blabla }

And I want to use the same line for a different class like :

    $('.anotherclass').click(function(){ blabla }

Now ... how can I use the same click function without redeclaring it ? i want something like :

          ($('.buythis'),$('.anotherclass')).click(function(){ blabla }
like image 250
mr.Liviu.V Avatar asked Aug 10 '11 09:08

mr.Liviu.V


2 Answers

Try this:

 $('.buythis, .anotherclass').click(function(){ blabla }
like image 119
Mr.T.K Avatar answered Oct 05 '22 22:10

Mr.T.K


Use a comma between the two selectors:

$('.buythis, .anotherclass').click( ... );

or use two selectors chained with .add().

$('.buythis').add('.anotherclass').click( ... );

The latter syntax can be useful if the selectors are complicated since it can remove ambiguity from the selector parser and make the code easier to read.

like image 37
Alnitak Avatar answered Oct 05 '22 23:10

Alnitak