My toggle function is only toggling through 2 of the 3 classes and not the third. It skips my star class and just toggles between my fact and barr classes. I’ve changed things around a bunch of ways and it’s only toggling through 2 of 3 classes.
My Html
<div id="labalt"><a href="#">Alt</a></div>
<h1 id="build_title" class="barr" >Barracks</h1>
My code
$("#labalt").click(function() {
$(this).toggleClass("fact star barr");
if($(this).hasClass("fact"))
{
$("#build_title").html("Factory");
}
else if($(this).hasClass("star"))
{
$("#build_title").html("Starport");
}
else
{
$("#build_title").html("Barracks");
}
});
Are you trying to get the code to cycle through all three texts on three consecutive clicks? Because that’s not what
toggleClassdoes.toggleClasstoggles one or more classes on or off.As you can tell by this fiddle, clicking the link toggles both the border, the font size, and the italics class.
It starts off with none of the classes. On click 1, it will have all three classes. It will then match the first condition (it has the
factclass), and since they areelse if‘s, no other conditions will be checked. The text will simply be set to “Factory”.On a second click, all three classes will be removed. It will not meet the first criteria (
fact) or the second (star), so it will set the text to “Barracks”.On a third click, all three classes will be added again.
If you want it to cycle through the classes, you’d have to implement that manually; I do not know that there is any out of the box solution for that. You would either need to keep a cursor of some kind, or continuously iterate an array to check whichever class is currently active, and then move on to the next. Example; I’m sure it could be neater.