Font Awesome icons within a nested accordion created using Bootstrap

I have a bootstrap accordion with 3 levels of nesting that is functioning correctly, but I want to make a change in the panel-heading div where I can use a font-awesome icon fa fa-chevron-down when the accordion is open (without affecting the nested accordions) and fa fa-chevron-right when the accordion is closed. Here is the code snippet I am using to change the icon:

$('div.panel-collapse.collapse').on('shown.bs.collapse', function() {
  $(this).parent().find(".fa-chevron-right").removeClass("fa-chevron-right").addClass("fa-chevron-down");
  $(this).parent().find('.panel-heading').css('background', '#0271BC');
}).on('hidden.bs.collapse', function() {
  $(this).parent().find(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-right");
  $(this).parent().find('.panel-heading').css('background', '#02A4EF');
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">

<a href="#aspnetcore" class="accordion-toggle tutorial-panel-heading" data-toggle="collapse" data-parent="#accordion">
... (Accordion HTML structure continues)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

However, this code also changes the icons of nested accordions that are not currently open. If you have any suggestions on how to improve this issue, please let me know.

Answer №1

In my approach, I find it effective to utilize examples from the Bootstrap documentation and manipulate icons using CSS toggle.

I also incorporated Font Awesome icons as part of the content within the :after pseudo-element.


Bootstrap 4

Borrowing concepts from the Accordion example.

To see the end result: CodePen

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css');
@import url('https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');

.mb-0 > a {
  display: block;
  position: relative;
}
.mb-0 > a:after {
  content: "\f078"; /* fa-chevron-down */
  font-family: 'FontAwesome';
  position: absolute;
  right: 0;
}
.mb-0 > a[aria-expanded="true"]:after {
  content: "\f077"; /* fa-chevron-up */
}</pre>

<footer>
    Scripts:
    <ul>
        <li><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></li>
        <li><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script></li>
    </ul>
</footer>

<hr>

<h2>Bootstrap 3</h2>

<p>Following the guidelines outlined in the <a href="https://getbootstrap.com/docs/3.3/javascript/#collapse-example-accordion" rel="nofollow noreferrer">Accordion example</a>.</p>

<p>For visual representation: <a href="https://codepen.io/glebkema/pen/xYPyeq" rel="nofollow noreferrer">CodePen</a>  •  <a href="https://jsfiddle.net/glebkema/1wx4ubvc/" rel="nofollow noreferrer">JSFiddle</a></p>

<pre class="snippet-code-css lang-css"><code>@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
@import url('https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');

.panel-title > a {
  display: block;
  position: relative;
}
.panel-title > a:after {
  content: "\f078"; /* fa-chevron-down */
  font-family: 'FontAwesome';
  position: absolute;
  right: 0;
}
.panel-title > a[aria-expanded="true"]:after {
  content: "\f077"; /* fa-chevron-up */
}
Scripts:

Answer №3

Here is a demonstration of how to initially display icons correctly using jQuery and Bootstrap.

I hope you find this example useful!

$(function(){
 $('.panel-title a[data-toggle="collapse"]').on('click', this, function(event) {
  
  $('.panel-collapse').on('show.bs.collapse', function () {
   $(this).siblings('.panel-heading').find('i').removeClass('fa-plus-circle').addClass('fa-minus-circle');
  });

  $('.panel-collapse').on('hide.bs.collapse', function () {
   $(this).siblings('.panel-heading').find('i').removeClass('fa-minus-circle').addClass('fa-plus-circle');
  });

 });
});
<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>

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">


<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">

<!-- Panel -->
<div class="panel panel-default">
  <div class="panel-heading" role="tab" id="item001">
    <h4 class="panel-title">
      <a role="button" data-toggle="collapse" data-parent="#accordion" href="#detail001" aria-expanded="true" aria-controls="detail001">
      <div class="title">Title 1 <i class="fa fa-minus-circle" aria-hidden="true"></i></div>
    </a>
    </h4>
  </div>
  <div id="detail001" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="item001">
    <div class="panel-body">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
  </div>
</div>
<!--/ Panel -->

<!-- Panel -->
<div class="panel panel-default">
  <div class="panel-heading" role="tab" id="item002">
    <h4 class="panel-title">
      <a role="button" data-toggle="collapse" data-parent="#accordion" href="#detail002" aria-expanded="true" aria-controls="detail002">
      <div class="title">Title 2 <i class="fa fa-plus-circle" aria-hidden="true"></i></div>
    </a>
    </h4>
  </div>
  <div id="detail002" class="panel-collapse collapse" role="tabpanel" aria-labelledby="item002">
    <div class="panel-body">
      Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
  </div>
</div>
<!--/ Panel -->

</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

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...

How can I retrieve my cropped image using Symfony2 Cropit?

My experience with this plugin has been disappointing. As someone new to JS/Jquery, I really needed this plugin for my website. That's why I came across cropit here: I struggled to figure out how to retrieve my cropped image in my controller and save ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Create a custom slider using jQuery that pulls in real-time data for a dynamic user

My goal is to implement a dynamic slider feature in my Django project by using jQuery and ajax. I have managed to create previous and next buttons for swiping through profiles with the help of others, but I am currently facing an issue with a NoReverseMatc ...

Issue with alignment on the printed version of an HTML document

While attempting to print an auto-generated HTML page through my Thermal POS printer, I encountered a large left margin issue. The application is developed using PyQt5, and I had to resort to a python script to generate the HTML code. Unfortunately, in the ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Most effective method for automatically scrolling down upon page load

Below is the code snippet that I am using: <script type="text/javascript"> window.onload = function () { window.scrollBy(0, 100); } </script> The purpose of this code is to scroll down after the page has fi ...

Hide, show, toggle, or empty elements using jQuery

I am having trouble getting this jQuery code to function properly. Within a div, there is a paragraph that I want to hide when a specific button is clicked and show when another button is clicked. Check out the code here $("#details").on("c ...

Tips for eliminating the pesky "ghost" line that appears in your coded HTML email

Check out this Sample Code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <title></title> & ...

Navigating through HTML content and extracting specific elements

After using an ajax call to retrieve the partialView HTML of a page, I need to extract information from the main div before displaying it. This data specifically relates to the size information in order to create a floating window. Here is the code snippe ...

Implementing a jQuery full-screen scroller with AJAX functionality

Having an issue with implementing Jquery fs scroller on my website. The challenge is that I want to add a scrollbar through fs scroller using an ajax call on certain pages, but the js library doesn't load properly in the ajax success function. Can som ...

In HTML 5, you can use either #Header or the <header> tag

I'm feeling a bit puzzled about html right now, so I have a question regarding the use of semantic elements: Should I structure my code like this? <html> <head> <title>Some page</title> </head> <body> < ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

Looking for a way to make one image disappear briefly while transitioning to another image in Javascript

**Hey there, coding enthusiasts! I could really use some help right now. I am trying to create a smooth image transition effect using Javascript, where one image fades out while the next one fades in seamlessly. As someone who is still relatively new to pr ...

Sending a PHP variable to a JavaScript function

When attempting to pass a value to a JavaScript function by clicking a link, I encountered an error message: Uncaught SyntaxError: Unexpected identifier The following is the code snippet: <?php include_once("php_includes/check_login_status.php") ...

Tips for controlling the placement of divs on a webpage

I need to align 3 divs in a specific way on my webpage. One should be on the left side taking up 25% of the window, one on the right side also taking up 25%, and the last one in the center taking up the remaining space. I'm struggling with how to achi ...

Creating a sidebar that remains fixed in place even as the page is scrolled down can be achieved by using CSS and positioning properties

I am looking to create a website with a specific layout design as shown in this image: https://i.stack.imgur.com/ndKcz.png The main focus is on making the sidebar (F/T container) function as a social network link, sticking to the right side of the page ev ...

Directories within directories - HTML base directories & subdirectories

Within my HTML, I have included the following code: <head> <base href="http://mydomain.com/dev/"> </head> Despite this base element setting, all of my links seem to be pointing to mydomain.com/ instead of the expected subfolder /dev/. ...

Struggling to eliminate the padding beneath the menu items in Bootstrap?

I'm having trouble adjusting the padding inside my menu. I want to make it less chunky and large, but so far I've only been successful in removing the top padding. The bottom padding just won't budge. Here's the code that helped fix th ...

Aligning content within a div block

I created a div block that houses a form structured like this: <div class="divClass"> <form id="frm" method="post" action="/NotDefinedYet/index.xhtml" class="frmClass"> <input type="text" name="j_idt9:j_idt10:Username" placehold ...