I am trying to create a collapsible panel group using Bootstrap, and I would like the panel heading to change background colour when the panel group is not collapsed (one colour for collapsed panel group, one for unwrapped). I have tried using the :active selector, but this changes the colour only when clicked, it does not persist longer:
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<a data-toggle="collapse" class="panel-title" href="#collapse1">Title</a>
</div>
<div id="collapse1" class="panel-collapse collapse">
<ul class="list-group">
<li class="list-group-item">item 1</li>
<li class="list-group-item">item 2</li>
</ul>
</div>
</div>
</div>
.panel-heading a:active {
background: red;
}
https://jsfiddle.net/s625dgty/
I would appreciate any suggestions.
Use .active
class instead of :active
pseudo-class which only lasts as long as the user keeps their mouse-button (or pointing device equivalent) down. Target the link's parent .panel-header
instead:
$('.panel-heading').on('click', function(e) {
$(this).toggleClass('active');
});
The CSS has been modified to override .panel-heading
with higher specificity by doubling the class:
.panel-heading.panel-heading {...
Some Bootstrap classes cannot be overridden by cascading priority, just double up on the target class as shown above -- do not use !important
Also, place <link>
in the <head>
. Place <script>
before the closing </body>
tag. See Demo.
.panel-heading.panel-heading.active {
background: red;
}
.panel-title {
display: inline-block;
width: 100%;
}
.panel-heading.panel-heading.active .panel-title {
color: white;
font-weight: 900;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<a data-toggle="collapse" class="panel-title" href="#collapse1">Title</a>
</div>
<div id="collapse1" class="panel-collapse collapse">
<ul class="list-group">
<li class="list-group-item">item 1</li>
<li class="list-group-item">item 2</li>
</ul>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
$('.panel-heading').on('click', function(e) {
$(this).toggleClass('active');
});
</script>
</body>
</html>