Santiago Welbes
Santiago Welbes

Reputation: 5

.toggleClass not working

I have what I thought to be a simple jquery task. I have an accordion. I don't have full control of the code because it's a wordpress thing.

I gave the accordion title this code:

<div class="teamTitle teamTitleDown">Jordan Gales | Job Title</div>

Then, I added this jquery:

$(".accordion-title").click(function() { $(".teamTitle").toggleClass("teamTitle")});

The classes add a fontAwesome icon. It's originally a left caret, and then when you click it becomes a down caret.

The toggle class only works once. When I click, I see in the inspect tool that the class teamTitle goes away. And visually, I see the icon change from left caret to down caret.

But nothing happens anymore upon subsequent clicks. I expect the class teamTitle to be toggled on/off every time I click.

Do I have a code error, or am I not understanding toggleClass correctly?

If it matters, here's the CSS for those two classes:

.teamTitle:after {
content: '\f0da'!important;
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
margin:0px 0px 0px 10px;
text-decoration:none;
}

.teamTitleDown:after {
content: '\f0d7';
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
margin:0px 0px 0px 10px;
text-decoration:none;
}

Upvotes: 0

Views: 1438

Answers (2)

Santiago Welbes
Santiago Welbes

Reputation: 5

I figured it out. Rookie mistake.

I used the selector $(".teamTitle") for the toggling, but then I toggled the same class. So after I clicked once, it toggled that class. But now that class was gone so I couldn't select it anymore.

I simply changed to $(".teamTitleDown") and now it works just fine

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21495

$(".teamTitle").toggleClass("teamTitle")}

This works the first time, because $('.teamTitle') matches the elements you want to match, and removes the 'teamTitle' class from them.

The second time it does not work, because $('.teamTitle') doesn't match any elements, because you already removed the classname you're trying to match against.

Either store the list of DOM elements and reuse it instead of matching by classname every time:

var foo = $('.teamTitle');
// from now on, foo.toggleClass('teamTitle') will operate on the same elements (as long as foo remains in scope!)

Or else put an additional classname onto those elements which you won't be toggling on and off, and use that to identify the elements:

<div class="foo teamTitle teamTitleDown">Jordan Gales | Job Title</div>

$('.foo').toggleClass('teamTitle')

Upvotes: 1

Related Questions