MagTun
MagTun

Reputation: 6185

change .css class with jquery

I have this slidetoggle and I want the style of the open toggle to be different then the closed ones.

By default all the faqtopics1 are set to border-radius: 5px; background-color: #f2ecec; when the div faqtext associated opens.

When the toggle opens, I want the style of faqtopics1 to be set to the "OnClick Style"

border-radius: 5px 5px 0 0;
background-color: #dedcdc;

I found out about the .css() Method and could somehow make something up (line 2 and 3):

   $(".faqtopics1").click(function(event) {
        $("div.faqtopics1").css({"border-radius":"5px", "background-color":"#f2ecec"});
        $(this).css({"border-radius":"5px 5px 0 0", "background-color":"#dedcdc"});
        $("div.faqtext").stop(true).slideUp(400);
        $(this).next("div.faqtext").stop(true).slideToggle();
    });

But it's not a total success as even when I re-click on a toggle to close it, the OnClick style remains. Is there a better way to make what I want ?

Also I want to apply the same principal even if I click on faqtopics2, faqtopics3 or faqtopics4 div. (cf the jsfiddle).

You can find my codes (css + query) on this jsfiddle

Thanks a lot for your help!

Upvotes: 0

Views: 82

Answers (3)

user3122094
user3122094

Reputation: 241

try this,

$('faqtopics1').attr('class','newClassName');

Upvotes: 1

Martin
Martin

Reputation: 7714

Something much easier:

Define your two states in CSS:

faqtopics1 {
  border-radius: 5px; 
  background-color: #f2ecec;
}

.onclickstyle {
  border-radius: 5px 5px 0 0;
  background-color: #dedcdc;
}

Then in JS you just have to toogle the class:

$("div.faqtopics1").toggleClass("onclickstyle");

This means you have a clear separation between the exact style (in the css), and the dynamic toogle (in the javascript).

Upvotes: 2

livinzlife
livinzlife

Reputation: 873

It may be easier to use addClass.

$this.addClass('active');

Then in your css

.faqtopics.active{border-radius:5px 5px 0 0; background-color:#dedcdc;}

You can give all of your "FAQ topics" a shared class .faqtopics and then unique id's #faqtopic1 #faqtopic2 if you need to style them a bit differently.

Upvotes: 1

Related Questions