Is there a way to specifically target the accordion panel header of Bootstrap upon being clicked?

I am currently utilizing Bootstraps collapse (accordion) feature and I want to modify the background color of the .panel-header when it is open. My current code snippet is close, but I have encountered an issue.

$('.panel-group').on('show.bs.collapse', function () {
     $(this).find('.panel-heading').addClass('active-panel');
});

$('.panel-group').on('hide.bs.collapse', function () {
     $(this).find('.panel-heading').removeClass('active-panel');
});

The challenge lies in the fact that the .panel-group (refer to documentation link above for structure) is the parent element of all .panel-headings, resulting in all panels receiving the .active-panel class. How can I target only the panel heading that was clicked?

Answer №1

Hope this solution proves helpful for you.

$('.panel-collapse.in').siblings('.panel-heading').addClass('active');
  $('.panel-collapse').on('show.bs.collapse', function () {
    $(this).siblings('.panel-heading').addClass('active');
  });

  $('.panel-collapse').on('hide.bs.collapse', function () {
    $(this).siblings('.panel-heading').removeClass('active');
  });
.active{
  background:#FF0 !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingThree">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Any tips or hacks for successfully implementing vw resizing on the :before pseudo-element in webkit browsers?

When using vw sizes on webkit browsers, a well-known bug can occur where they do not update when the window is resized. The typical workaround for this issue has been to employ javascript to force a redraw of the element by reassigning the z-index upon res ...

How can one ascertain the dimensions of the video margins within an embed-responsive video container?

I am in search of a solution to extract information from within the embed responsive element. When it comes to embed-responsive video elements, they automatically include internal margins on either the x or y axis to maintain the aspect ratio of the video ...

Customize the appearance of a hyperlink

I am having difficulty styling a link's title using jQuery-mobile. Each link represents a player with unique abilities. When the user hovers over a player, I want a tooltip to display their special ability. Despite trying various code samples, none ha ...

Ways to display the content of a specified URL in a new window for printing using JavaScript, jQuery, or ASP

Is there a way to open a URL in a new window as a print window rather than a normal window? I know how to open a new window using window.open(url); but I specifically need it to be a print window. ...

Preventing access to drives and desktop until the mandatory HTML form is completed

Looking to develop a webpage in JSP that will automatically open whenever my system is started. Users will be required to fill out a form on this page before proceeding further. If they attempt to bypass filling out the form, they should not have access ...

How jQuery can identify a class even after it has been removed

I need to implement a universal 'locked' class that would disable user interaction with any elements (such as anchors, buttons, etc.) while a block is loading. It's a simple loading lock without any fancy or secure features. My approach inv ...

Utilize Bootstrap's collapsible navbar feature to smoothly navigate to a designated section of the webpage

After creating a navigation bar using bootstrap 4, I encountered an issue when trying to collapse the navbar and jump to an anchor simultaneously in mobile view. If I only include href="#services", it successfully jumps to the correct section of ...

Dimensions of Embedded Instagram Content

I attempted to integrate an Instagram photo into my iOS Swift application by following the instructions provided on the Facebook developers website. However, I encountered an issue where the Instagram post did not adjust its width to fit within the designa ...

Disable the off-canvas sidebar when a link is clicked in Jasny Bootstrap

Working on a website located at When viewing the site on mobile devices ( < 768px ), I am struggling with getting the off-canvas navigation to automatically close after clicking on one of its links. Any assistance would be greatly appreciated as I&apos ...

What is the best way to handle JSON data errors when a value is undefined?

I am currently working on a piece of code that displays JSON data in HTML. However, if a value is undefined, it doesn't display anything. How can I handle this error so that if a value is undefined, it will show "N/A" instead of breaking the code? ...

Arranging Bootstrap divs vertically and then horizontally in mobile view

My website layout is relatively straightforward. It consists of a header at the top, a navigation bar with an image inside a column on the left, and the main content displayed on the right side. https://i.stack.imgur.com/yYzaG.png For mobile responsive vi ...

Sending Data to PHP Script Using AJAX Without Submitting the Form

Seeking assistance with capturing onclick event for image deletion. I have a code snippet below that triggers an 'onclick' event for deleting images which calls the 'delete.php' script to remove physical images from the server. <sc ...

Event fails to trigger when attached to different elements

Currently, I have an onchange event linked to the input text box and an onclick event attached to a text link. Interestingly, when I click on the link after editing the textbox, the click event does not trigger - instead, the change event is fired. If you ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

The width attribute is not being applied in Internet Explorer's compatibility modes

When I try to apply the following CSS, the width does not get applied in IE Compatibility modes: .multipleShipmentsGrid { border-color:#949EAA; border-style:solid; border-width:1px; width:80%!important; border-collapse:collapse; } How ...

What is the best way to conceal a modal using jquery?

Click button to open modal: <button type="button" class="btn" onclick="CountClass()" runat="server" data-toggle="modal" data-target="#inlineForm1">OPEN</button> The modal code: <div class="modal fade text-left" id="inlineForm1" tabindex=" ...

What could be causing the error message "(#tabs).tabs is not a function" in the context of setting up JQuery in Rails 3.1.3?

When attempting to load the login page on localhost:3000, an error in the application.js file appears in firebug causing the page to hang. The Gemfile contains: gem 'jquery-rails', '~>1.0.19' The error-causing code (including the r ...

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

Position elements to the right side of a flex container

I'm utilizing Bootstrap 4 along with this CSS class to vertically align my elements: .vertical-align { display: flex; flex-direction: row; } .vertical-align > [class^="col-"], .vertical-align > [class*=" col-"] { display: flex; align-i ...

Identify and target a particular DIV based on the URL for customization

My webpage has a collection of frequently asked questions (FAQs) on a page called faq.html. Here is an example structure: <div id="faq1">...</div> <div id="faq2">...</div> I am looking to create a pulsating or highlighting effect ...