Mike E
Mike E

Reputation: 153

Active state on Bootstrap Acccordion click

I am using Bootstrap accordion to show/hide content using the code below. The javascript code applies an active class to the panel heading to change the background colour to green, with white font. This works ok but I need the .question span class to also change font color when the panel heading is clicked. I have tried targeting the .question class to add the active class but it has no affect?

HTML

<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse1">
<span class="question">Q:</span>First Question</a></h4></div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">
<span class="answer">A:</span> Text </div>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse2">
<span class="question">Q:</span>Second Question</a></h4></div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
<span class="answer">A:</span> Text</div>
</div>
</div>

JS

 $('.panel-heading').click(function() {
$('.panel-heading').removeClass('active');
$(this).addClass('active');

$('.question').removeClass('active');
$(this).addClass('active');

});

CSS

.active {
background-color: green!important;
color: white!important;
}

.question {
color: blue
}

Upvotes: 0

Views: 4024

Answers (1)

KavehG
KavehG

Reputation: 323

You can achieve that with pure CSS, just use bootstrap set attribute aria-expanded:

.panel-heading a[aria-expanded='true']>span.question {
    color: red;
}

.panel-heading a[aria-expanded='false']>span.question {
    color: blue;
}

Upvotes: 2

Related Questions