I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet.
In certain scenarios, the first panel is open by default on page load, indicated by the class show
. My objective is to have the background of this card header turn red on page load as well.
The buttons in the card headers are controlled using JavaScript, as shown in the code snippet.
I believe I need to use JavaScript to toggle classes.
Initially, I created a new class called highlight
and included the following CSS:
.accordion .card-header.highlight {
color: #fff;
background-color: red;
}
Subsequently, I added the following JavaScript code (please note that I find JavaScript challenging to grasp, but I am slowly learning) in an attempt to set the background of the header of the open panel on page load.
$(document).ready(function(){
// Add class highlight to panel with show class
$(".collapse.show").each(function(){
$(this).prev(".card-header").addClass("highlight");
});
// toggle highlight class
$(".card-header .btn").click(function(){
$(".card-header").toggleClass("highlight");
});
});
It may seem messy, and it doesn't yield the desired outcome.
How can I set the background (red) of the header of the open panel on page load and how can I toggle classes using JavaScript?