How to Make Bootstrap 3 Collapse Panels Stand Out with an Active Class

First of all, here is the fiddle link: http://jsfiddle.net/krish7878/h38jn324

I have a simple question. When a panel is clicked and it expands to show its contents, a class 'active' should be added to 'panel-heading'.

I came across a similar question but none of the solutions provided seemed to work for me. Any assistance would be greatly appreciated.

HTML Code:

<div class="accordion-2 panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                    Our Mission
                </a>
            </h4>
        </div><!-- /.panel-heading -->
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
            </div>
        </div><!-- /#collapseOne -->
    </div><!-- /.panel -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
                Success Stories
            </a>
        </h4>
    </div><!-- /.panel-heading -->
    <div id="collapseTwo" class="panel-collapse collapse">
        <div class="panel-body">
            <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
        </div><!-- /.panel-body -->
    </div><!-- /#collapseTwo -->
</div><!-- /.panel -->
<div class="panel panel-default last">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
                Our Story
            </a>
        </h4>
    </div><!-- /.panel-heading -->
    <div id="collapseThree" class="panel-collapse collapse">
        <div class="panel-body">
            <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
        </div><!-- /.panel-body -->
    </div><!-- /#collapseTwo -->
</div><!-- /.panel -->

JS Code:

jQuery('.accordion-2 .panel-heading a[data-toggle="collapse"]').on('click', function () {
jQuery('.accordion-2 .panel-heading a[data-toggle="collapse"]').removeClass('actives');
$(this).addClass('actives');

});

Answer №1

Give this a try:

$('.panel-heading a').click(function() {
    $('.panel-heading').removeClass('active');
    if(!$(this).closest('.panel').find('.panel-collapse').hasClass('in'))
        $(this).parents('.panel-heading').addClass('active');
});

View JSFiddle Demo

Update 1: For the panel to be active by default on initial load, manually add the active class to the panel-heading in the HTML code.

Update 2: While this answer is accepted, it's recommended to also consider the response from user Blizwire.

Answer №2

Instead of using a standard click event, Moshtaf's current answer suggests utilizing Bootstrap's built-in event for opening and closing collapsible items, as highlighted by Jurriaan. This method is considered safer since a click on the link does not necessarily indicate that the panel is displayed. Building upon Jurriaan's solution, here is a streamlined approach with minimal code and jQuery selectors for achieving the desired functionality. Check it out here.

$(document).ready(function() {
  $('.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');
  });
});

Answer №3

I encountered a few challenges with the previous solutions provided, such as dealing with multiple panel groups on one page or toggling the same panel by clicking on its title. After some modifications inspired by this Stack Overflow post, I found a more versatile approach that also includes code for setting the default open panel to an active state.

$('.panel-group .panel-collapse.in').prev().addClass('active');
$('.panel-group')
  .on('show.bs.collapse', function(e) {
    $(e.target).prev('.panel-heading').addClass('active');
  })
  .on('hide.bs.collapse', function(e) {
    $(e.target).prev('.panel-heading').removeClass('active');
  });

Answer №4

Looking for a CSS solution, I successfully implemented this code in Bootstrap 4:

HTML

<a class="collapsed" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Open Collapse </a>

<div class="collapse" id="collapseExample">
  <div class="card card-block card-outline-primary">
    <h3 class="text-center">Date Goes Here</h3>
  </div>
</div>

CSS

[data-toggle="collapse"]:not(.collapsed) {
  background-color: blue;
}

Answer №5

$(function() {
  $('.panel-heading').click(function() {
    if ($(this).hasClass('activestate')) {
      $(this).removeClass('activestate');
    } else {
      $('.panel-heading').removeClass('activestate');
      $(this).addClass('activestate');
    }
  });
});
a,
a:hover,
a:active,
a:focus {
  text-decoration: none !important
}
.panel-heading:hover,
.panel-heading:focus,
.panel-heading:hover a,
.panel-heading:focus a {
  color: #c9b27e;
  text-decoration: none !IMPORTANT;
}
.activestate {
  background-color: #c9b27e !IMPORTANT;
  color: white !important;
  display: block;
}
.activestate:hover a {
  color: black;
}
.panel-heading {
  display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<div class="accordion-2 panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading activestate">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
        Our Mission
        </a>
      </h4>
    </div>
    <!-- /.panel-heading -->
    <div id="collapseOne" class="panel-collapse collapse in">
      <div class="panel-body">
        <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
          mollitia animi, id est laborum et dolorum fuga.</p>
      </div>
    </div>
    <!-- /#collapseOne -->
  </div>
  <!-- /.panel -->
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
         Success Stories
        </a>
      </h4>
    </div>
    <!-- /.panel-heading -->
    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
          mollitia animi, id est laborum et dolorum fuga.</p>
      </div>
      <!-- /.panel-body -->
    </div>
    <!-- /#collapseTwo -->
  </div>
  <!-- /.panel -->
  <div class="panel panel-default last">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
         Our Story
        </a>
      </h4>
    </div>
    <!-- /.panel-heading -->
    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt
          mollitia animi, id est laborum et dolorum fuga.</p>
      </div>
      <!-- /.panel-body -->
    </div>
    <!-- /#collapseTwo -->
  </div>
  <!-- /.panel -->
</div>
<!-- /.accordion-2 -->

I believe this arrangement makes more sense.

Answer №6

Unlike the other solutions that involve panel-heading, this answer only requires the data-target attribute.

$('[data-toggle=collapse]').each(function() {
    var $collapse_btn = $(this),
        $collapse_target =  $(this.getAttribute('data-target'));

    $collapse_target.on('show.bs.collapse', function () {
        $collapse_btn.addClass('collapsed');
    }).on('hide.bs.collapse', function () {
        $collapse_btn.removeClass('collapsed');
    });
});

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

Error encountered while parsing data in Internet Explorer versions 7, 8, 9, and 10 due to an invalid character. The status

This block of code is functioning correctly on Chrome and Firefox, however it seems to be having issues with Internet Explorer! It involves a simple JSON file call, fetching data, and then displaying it on an HTML webpage. Here's the code snippet: $. ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

Having trouble retrieving multiple selected values from the paper listbox in Polymer 3

I'm attempting to retrieve multiple selected values in a paper-listbox element in Polymer. <paper-dropdown-menu label="{{_getLabel('Activity Type')}}" id="fromMenu" on-paper-dropdown-close="fromAccountChanged" searchable="true"> ...

Exploring Angular: Looping through an Array of Objects

How can I extract and display values from a JSON object in a loop without using the keyValue pipe? Specifically, I am trying to access the "student2" data and display the name associated with it. Any suggestions on how to achieve this? Thank you for any h ...

Incorporating HTML content into a Vue component

I'm running into issues trying to display the content of an HTML file within a Vue component. Essentially, I have a Django backend that generates an HTML file using Bokeh and backtesting.py library. On the frontend side, I'm utilizing Nuxt/Vue, w ...

In Lightning Web Components, there seems to be an issue with the splice method not functioning correctly when used with an @api

When checking the console, I noticed that this.unselectedPlayerList.length is not displayed until after using the splice method. This has raised some doubts in my mind about how the splice method works. export default class MakeYourTeamChild extends Ligh ...

Check that a string field includes specific characters and digits using JavaScript

I'm in the process of developing a React application that includes an input field requiring a specific format: The first four characters (char 1,2,3, and 4) must be "VTF_" followed by numbers for the remaining part of the string. For example, VTF_12 ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...

Trouble arises when adding a .js script to the webpage

I'm feeling quite puzzled by this small piece of code, as it appears to be the simplest thing you'll come across today. Despite that, I can't help but seek guidance because I've been staring at it for what feels like an eternity and can ...

Tips for avoiding unnecessary re-renders when using a functional component and react hooks:

Problem: When a user enters a room code in the input field, the web application re-renders, causing the socket to disconnect and reconnect. Scenario: I am developing a multiplayer game using technologies like Socket.io, React, Express, PostgreSql, and Nod ...

jQuery is a logical operator that simplifies the process of

Three file inputs are included below: A File : <input type="file" name="AFile" id="AFile" /> B File: <input type="file" name="BFile" id="BFile" /> C File : <input type="file" name="CFile" id="CFile" /> To automatically upload all three ...

Tips on implementing live updates in Firebase without the need for reloading the page

After a user changes their profile picture, the update does not appear until they refresh the page. Here is the code snippet causing this issue: const handleProfile = async (e: any) => { const file = e.target.files[0] const storageRef = firebase ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

How can we make Internet Explorer 11 mimic Internet Explorer 9 in HTML?

How can I ensure that Internet Explorer 11 uses CSS styles from IE9 in my HTML? I have tried the following code: <script runat="server"> private void Page_PreRender(object sender, EventArgs e) { var meta = new HtmlMeta() ...

to streamline the process of navigating Google Chrome web pages

Is it possible to create automation in Google Chrome that can complete the following tasks: 1. Input a job name to monitor 2. Periodically click a refresh button on the webpage (not the refresh button for the entire Chrome page in the left corner) 3. Open ...

Flowtype: Utilizing type hints for class-based higher order component

I am currently working on typehinting a higher-order component (HOC) that adds a specific prop to a passed Component. The code snippet looks like this: // @flow import React, { Component } from 'react'; import type { ComponentType } from 'r ...

Integration of Angular.js functionalities within a Node.js application

After working on my node.js app for a few weeks, I decided to add some additional features like infinite-scroll. To implement this, I needed to use packages in node.js along with angular.js. So, I decided to introduce angular.js support to the app, specifi ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...