Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery problem onclick add class and remove class

first time posting here. I'm a beginner in jquery and i ran into some grey area. Hopefully i can find my answer here and learn from it also :)

So i have a let's say 10 different div. All has the same class. And everytime I click on the div it has to add another class (in this case background-color in css). For that I have this:

$(document).ready(function() {
$(".menucardmenu").click(function(){
        if($(this).hasClass("menucardmenu")) {
               $(this).addClass("backgroundmenucard");
    }
    else {
        alert ("condition false");
    }
  });
});

But the question now is, how can i make that only one div can have that background-color (in my case backgroundmenucard). Depending one which div the user click, that div will have the background-color, and the previous div (that was clicked) should reset it back to normal. I can do it with this right?:

$(this).removeClass("backgroundmenucard");

does anyone know the answer to this???

Regards, Andrew

like image 372
Andrew Ng Avatar asked Feb 22 '26 08:02

Andrew Ng


1 Answers

try the following:

$(".menucardmenu").click(function(){
    $(".backgroundmenucard").removeClass("backgroundmenucard");
     $(this).addClass("backgroundmenucard");
  });

Demo: http://jsfiddle.net/r2Sua/

(I remove the if because it's useless in this case)

like image 60
Sotiris Avatar answered Feb 24 '26 21:02

Sotiris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!