SAD
SAD

Reputation: 57

jQuery UI class switching of multiple elements

Im trying to make the divs change class from "normal" to "thin" ONLY if they have the class "normal". But somehow they just change back and forth, the IF statement seems to be written completely wrong :)

Here is the code

<div class="normal">1</div>
<div class="normal">2</div>
<div class="normal">3</div>
<div class="normal">4</div>
<div class="normal">5</div>
<div class="normal">6</div>

CSS:

.normal{
float:left;
height:200px;
width:100px;
border:1px dotted gray;
}

.thin{
float:left;
width:50px;
height:200px;
border:1px dotted gray;
background-color:#5a5a5a;
}

jQuery

$(document.body).click(function () {
  $("div").each(function () {
    if ($(this).hasClass("normal")) {
      $(this).toggleClass("thin", 300);         //Problem here?
    } else {
      this.style.color = "red";
    }
  });
});

Upvotes: 1

Views: 301

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76436

You didn't remove the 'normal' class after you have first reached the code block of your if and your div will always have the 'normal' class, so your condition in your if will always be true.

Use removeClass for that purpose.

Also, if you want to change the class from 'normal' to 'thin', use the addClass for adding thin instead of toggle.

EDIT: Maybe this is what you want:

$(document.body).click(function () {
  $("div").each(function () {
    if ($(this).hasClass("normal")) {
      $(this).removeClass("normal");
      $(this).addClass("thin");
    }
    else if ($(this).hasClass("thin")) {
      $(this).removeClass("thin");
      $(this).addClass("normal");
    } else {
      this.style.color = "red";
    }
  });
});

Upvotes: 0

uhleeka
uhleeka

Reputation: 698

ToggleClass (http://api.jquery.com/toggleClass/) will both add and remove the class. So instead, you want to remove the class "normal" and add the class "thin":

$(this).removeClass("normal").addClass("thin");

Regarding the animation, it looks like you are using the jQueryUI project (sorry I missed the tag, the first time around): http://jqueryui.com/toggleClass/ which allows you to specify an animation duration. With that in mind, you can include the durations:

$(this).removeClass("normal", 300).addClass("thin", 300);

Upvotes: 1

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

@Egis as per your requirement the code should like below :

$(document.body).toggle(
    function () {
        $("div.normal").animate({
            width: "50px",
        }, "slow", function(){ $(this).addClass("thin"); });
    },
    function(){
        $("div.normal").animate({
            width: "100px",
        }, "slow", function(){ $(this).removeClass("thin"); });
    }
);

DEMO

I hope this is what you are looking for, Good Luck !!

Upvotes: 2

Related Questions