Liz Liz - 27 days ago 8
jQuery Question

JQuery Active toggle/add/remove class issue

I have an app where you can choose any combination of 6 divs as selected or not (marked by class

active
), then a 7th div which when selected clears all the others. I have the jquery working except for the addition of the
active
class to the 7th div. Here's a fiddle:



$( document ).ready(function() {
$('.q4-answer').on('click', function() {
$(this).toggleClass('active');
});
$('#q4-all').on('click', function() {
$('#q4-all').addClass('active');
$('.q4-answer').removeClass('active');
});
});

.answer {
display: inline-block;
width: 10%;
border: solid thick white;
text-align: center;
}

.answer img {
width: 30px;
}

.answer.active {
background-color: yellow;
border: solid thick black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="q4-legs" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Legs</p>
</div>

<div id="q4-chest" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Chest</p>
</div>

<div id="q4-back" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Back</p>
</div>

<div id="q4-biceps" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Biceps</p>
</div>

<div id="q4-triceps" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Triceps</p>
</div>

<div id="q4-shoulders" class="answer q4-answer">
<img src="http://icons.iconarchive.com/icons/iconka/meow/256/cat-grumpy-icon.png" />
<p>Shoulders</p>
</div>

<div id="q4-all" class="answer q4-answer">
<img alt="A full body workout. Huzzah!" src="https://s-media-cache-ak0.pinimg.com/236x/d3/11/eb/d311eb7f9e927ea7ba604387f6278558.jpg" />
<p>Full Body</p>
</div>





Can anyone figure out why that last problematic div isn't getting the
active
class when clicked?

Answer

When you click 7th div (Full body dog), you are adding first a class 'Active' to him and then removing all classes, so it removes his class too. You simply need to change order. This should work:

$( document ).ready(function() {
    $('.q4-answer').on('click', function() {
       $(this).toggleClass('active');
    });
    $('#q4-all').on('click', function() {           
       $('.q4-answer').removeClass('active');
       $('#q4-all').addClass('active');
    });
});
Comments