Swapping the icon in the panel heading of Bootstrap 3 Collapse based on its collapse status

Despite many attempts, I haven't been able to make any of the provided answers work in my code.

My setup involves using Bootstrap 3 panels and collapse functionality to display advertisements. In the default view, only the advertisement heading is visible along with a chevron down icon indicating additional information available.

Upon clicking the chevron-down icon, the main panel body with the advertisement text should be revealed. At this point, I'd like the chevron-down icon to change to a chevron-up icon.

The script I'm currently using looks like this:

<script language="JavaScript" type="text/javascript">
  $('#Advert').on('show.bs.collapse', function(){
    $('#Glyp-Advert').removeclass('glyphicon glyphicon-chevron-down').addclass('glyphicon glyphicon-chevron-up');
  });
  $('#Advert').on('hide.bs.collapse', function() {
    $('#Glyp-Advert').removeclass('glyphicon glyphicon-chevron-up').addclass('glyphicon glyphicon-chevron-down');
  });
</script>

<div class="panel panel-default">
  <div class="panel-heading">
    <h4 class="panel-title">
      <a id="Heading-Advert" data-toggle="collapse" data-parent="#accordion" href="#Advert">
        Heading
        <span class="pull-right"><span id="Glyp-Advert" class="glyphicon glyphicon-chevron-down"></span></span>
      </a>
    </h4>
  </div>
  <div id="Advert" class="panel-collapse collapse">
    <div class="panel-body">
      Advert text<br />
    </div>
  </div>
</div>

While the above code successfully displays the main advert panel, it doesn't update the icon as intended.

If anyone can provide some guidance, I would greatly appreciate it. Keep in mind that there will be multiple ad placements on the page, so I plan to duplicate the code but modify the IDs to include 'Advert1' or 'Advert2' etc rather than just 'Advert'.

Answer №1

Remember, JavaScript is a case-sensitive language.

Therefore, please note that using removeclass and addclass will result in errors. The correct method names are removeClass and addClass with a capital 'C' for each.

Rest assured, your code functions properly otherwise. You can view an example at http://jsfiddle.net/wilsonjonash/SXYZ2/

Answer №2

The response provided by Jonathan Wilson was accurate, however it overlooked the crucial detail that the script must come after the HTML content in my example code.

Therefore, to ensure correct functionality, the revised code should be as follows:

<div class="panel panel-default"><div class="panel panel-default">
  <div class="panel-heading">
    <h4 class="panel-title">
      <a id="Heading-Advert" data-toggle="collapse" data-parent="#accordion" href="#Advert">
        <span class="pull-right"><span id="Glyp-Advert" class="glyphicon glyphicon-chevron-down"></span></span>
        Heading
      </a>
    </h4>
  </div>
  <div id="Advert" class="panel-collapse collapse">
    <div class="panel-body">
      Advert text<br />
    </div>
  </div>
</div>
<script language="JavaScript" type="text/javascript">
  $('#Advert').on('show.bs.collapse', function(){
    $('#Glyp-Advert').removeClass('glyphicon glyphicon-chevron-down').addClass('glyphicon glyphicon-chevron-up');
  });
  $('#Advert').on('hide.bs.collapse', function() {
    $('#Glyp-Advert').removeClass('glyphicon glyphicon-chevron-up').addClass('glyphicon glyphicon-chevron-down');
  });
</script>

Answer №3

Forget about Javascript - you can achieve this using just a few CSS tricks. Let me show you how I tackled it.

  1. Ensure that all your links in the panel-title section have the accordion-toggle class

  2. Insert the following CSS into your style sheet:

.

/* display a symbol when panels are open */
.panel-heading .accordion-toggle:after {
    font-family: 'FontAwesome';
    content: "\f068";
    float: right;
    color: #474747;
}

/* display a different symbol for closed panels */
.panel-heading .accordion-toggle.collapsed:after {
    content: "\f067";
}

Please note, I used FontAwesome in my example, but feel free to customize the font and symbols according to your requirements, like using up and down arrows instead.

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

What is causing my navbar's 'ol' element to have a wider width than the

Hello, I have a navigation bar with a dropdown menu using ol. However, when I hover over the list items, the width of the list exceeds that of the ol element. I believe this is due to the white-space: nowrap CSS property, but I want the text in the dropdow ...

Troubleshooting a 400 Bad Request Error in jQuery Ajax for WordPress Widgets

I am attempting to send information to admin-ajax.php in order to save it as a $_POST variable for handling on the cart page. However, my .ajax function keeps failing. var sendJsonA = {'value':'Data coming from JSON'} var ajaxurl = $ ...

JQuery selecting and highlighting a row within a dynamically loaded table via ajax

On a webpage, there are two tables being displayed. The first table loads along with the entire page, while the second table is loaded later on using ajax. Each row in both tables contains links. Upon clicking a link, the corresponding row in the table ...

Display a progress bar on the index page of the grid view

Seeking assistance in displaying a progress bar on the grid view page index. Currently, I have successfully implemented a progress bar on button click and would like to replicate this functionality when the user switches from 1 to 2. Here is the modal pop- ...

Issues arise when attempting to utilize jQuery to print a string once a button is pressed

I am trying to display a string on the webpage when the user clicks a button. Below is the HTML code: <p> <h1 class="text-center" id="notif"> </h1> </p> Here is the relevant part of the script: $("#btn_My").click(functio ...

In a two-column layout, ensure that the text in the left box is aligned to the left and the text in the right box is aligned to the

I'm working on a flexbox layout with two columns, each containing text. The text in the left column is aligned to the left, while the text in the right column is aligned to the right. However, I want the text in the right column to switch to left al ...

Numerous CSS class attributes

I have been experimenting with creating my own custom progress bar using CSS. While the HTML5 <progress value="10" max="100"></progress> element could work, I prefer to create it from scratch. In my CSS code, I have defined the .progressbar c ...

Communication between Laravel and controller using AJAX for exchanging information

I have a specific AJAX function being called from a view: function gatherProductData() { var productIds = []; $('#compare-widget tbody tr').each(function(i, ele) { productIds[i] = $(ele).data('product-id'); }); ...

The Node.js server is failing to retrieve information from the AngularJS application

Having trouble reading data sent from an AngularJS client to the server via $http.post. Can't seem to figure out where I've made a mistake. var data = $.param({ id:$scope.user_id, }); alert(JSON.stringify(data)); $http.post('/getd ...

Altering the text field's content when the dropdown menu is modified

I have been attempting to modify the content of 5 text boxes whenever one of the 5 dropdown menus is altered. However, my current approach does not seem to be working as expected. All I want to do is transfer the selected value from the dropdown menu int ...

The duration for which an API Access Token remains valid is extremely brief

I recently started working with APIs and my current project involves using the Petfinder API v2 to develop a website that allows users to search for adoptable animals. The API utilizes OAuth, requiring a key and secret to obtain a token via CURL. However, ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

Issue with nested promises not functioning as anticipated within a for loop

I'm currently facing an issue with extending a Promise inside a .then() block. My goal is to update records in the database using a for-loop and then close the database after all updates have been processed. However, the application is exiting abruptl ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Can you please guide me on how to convert pug (jade) to html using npm scripts?

Struggling to construct my package.json file, I find myself facing a challenge when it comes to writing scripts. "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build-css":"node-sass --output-style compressed -o bu ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

Retain the spaces within a string in Java and JavaScript programming languages

My Java code sends data to the browser via an HTTP request, and the output looks something like this: JAVA CODE OUTPUT | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | | 0 | SELECT STATEMENT | | | | 3 ...

Dynamic image swapping using JSON key in Angular

Trying to display different icons based on a property that contains specific words. If the property includes "Health Care" or "Health Care .....", I want to show one image, otherwise another. I've tried using ng-show but my syntax seems off. Any sugge ...

Steps to hide a div with jQuery when a user clicks outside of a link or the div itself:1. Create a click event

Here's a simple question - I have a link that when clicked, displays a div. If the user clicks away from the link, the div is hidden, which is good. However, I don't want the div to be hidden if the user clicks on it. I only want the div to disap ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...