Rotating the icon in Bootstrap Accordion upon opening

I am trying to customize a Bootstrap 4 accordion by conditional rotating the icon to point up when it is open and back down when closed. I managed to achieve this using CSS, but now I need to implement it conditionally based on active states rather than events triggering the accordions open.

Here is the HTML structure:

<div class="accordion" id="accordion-nav">

    <div class="accordion-item">
        <div class="item-header" id="heading">
            <button class="btn btn-link btn-nav-accordion" type="button" data-toggle="collapse"
                data-target="#collapseDosing" aria-expanded="false" aria-controls="collapseDosing">
                <span>panel</span>
                <i class="fas fa-chevron-down "></i>
            </button>
        </div>

        <div id="collapseDosing" class="collapse collapse-nav-accordion"
            aria-labelledby="heading-dosing" data-parent="#accordion-nav">
            <div class="accordion-body">
                <div class="l-accordion-body">
                   <h1>Body</h1>>
                </div>
            </div>
        </div>
    </div>

    <div class="accordion-item accordion-item--savings">
        <div class="item-header" id="heading-savings">
            <button class="btn btn-link btn-nav-accordion" type="button" data-toggle="collapse"
                data-target="#collapseSavings" aria-expanded="false" aria-controls="collapseSavings">
                <span>panel</span>
                <i class="fas fa-chevron-down"></i>
            </button>
        </div>
        <div id="collapseSavings" class="collapse collapse-nav-accordion"
            aria-labelledby="heading-savings" data-parent="#accordion-nav">
            <div class="accordion-body">
                <div class="l-accordion-body">
                 <h1>Body</h1>
                </div>
            </div>
        </div>
    </div>
</div>

In my CSS, I styled the icon rotation on click event, but looking for an alternative conditional way using JavaScript:

.btn-nav-accordion[aria-expanded="true"] {
  .fa-chevron-down {
    transform: rotate(180deg);
  }
}

And here is my JavaScript code that currently works but does not remove the class upon closing the accordion:

 $(".collapse-nav-accordion").each(function () {
      var currentAccordion = this;
      if ($(currentAccordion).hasClass("show")) {
        $(currentAccordion).parent().find("i").addClass("rotate");
      } else {
        $(currentAccordion).parent().find("i").removeClass("rotate");
      }
    });

Answer №1

The main issue identified is the usage of SCSS code that requires compilation into CSS. In addition, the JavaScript code provided seems unnecessary for the current task.

.btn-nav-accordion[aria-expanded="true"] .fa-chevron-down {
  transform: rotate(180deg);
}

.fa-chevron-up {
    transition: all 0.3s ease;
 }
.btn-nav-accordion.collapsed .fa-chevron-up {
  transform: rotate(180deg);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="accordion" id="accordion-nav">

  <div class="accordion-item">
    <div class="item-header" id="heading">
      <button class="btn btn-link btn-nav-accordion collapsed" type="button" data-toggle="collapse" data-target="#collapseDosing" aria-expanded="false" aria-controls="collapseDosing">
                <span>panel</span>
                <i class="fas fa-chevron-up"></i>
            </button>
    </div>

    <div id="collapseDosing" class="collapse collapse-nav-accordion" aria-labelledby="heading-dosing" data-parent="#accordion-nav">
      <div class="accordion-body">
        <div class="l-accordion-body">
          <h1>Body</h1>
        </div>
      </div>
    </div>
  </div>

  <div class="accordion-item accordion-item--savings">
    <div class="item-header" id="heading-savings">
      <button class="btn btn-link btn-nav-accordion" type="button" data-toggle="collapse" data-target="#collapseSavings" aria-expanded="true" aria-controls="collapseSavin...;
        <span>panel</span>
        <i class="fas fa-chevron-up"></i>
    </button>
    </div>
    <div id="collapseSavings" class="collapse collapse-nav-accordion show" aria-labelledby="heading-savings" data-parent="#accordion-nav">
      <div class="accordion-body">
        <div class="l-accordion-body">
          <h1>Body</h1>
        </div>
      </div>
    </div>;
  </div>;
</div>;

Answer №2

Your code snippet includes an operation where you check if the element has a class of "show" and then toggle the class "rotate" accordingly. However, the functionality of the "rotate" class is not explicitly defined in your code. Could it be a CSS property such as

.rotate {transform: rotate(180deg);}
or perhaps a JavaScript behavior like
if (el.hasClass('rotate')) { el.style.transform = rotate(180deg); }
?

An alternative approach is to simply switch between classes depending on whether the "rotate" class is present, for example changing from fa-chevron-down to fa-chevron-up:

if (el.hasClass('rotate') { 
    el.classList.replace('fa-chevron-down', 'fa-chevron-up');
} else {
    el.classList.replace('fa-chevron-up', 'fa-chevron-down');
}

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

Navigation that sticks and changes upon hovering over div elements

Just delving into the world of jQuery and JS, so I appreciate your patience:) Currently, I have a sticky navigation bar positioned at the top of my webpage that links to different sections of content below. I am looking to create an effect where the corr ...

What could be causing this text to not center properly on mobile devices?

Here is the main content. There are no alignment commands in the CSS or HTML. Check out the jsfiddle: https://jsfiddle.net/9t4afmx3/ Any idea why it's left-aligned on mobile devices? <body> <p align="center"><img src="Screen Shot 20 ...

Trouble encountered when using RxJS zip and pipe together

In my Angular Resolver, I am facing a scenario where I need to wait for two server calls. The catch is that the second server call is optional and can be skipped based on user input. This data retrieval process is crucial for loading the next page seamless ...

What is the best way to automatically direct users to their profile page after logging in?

After logging in, I need to redirect users to their profile page. The issue I'm encountering is figuring out how to pass the user_id into the URL for successful redirection. I've researched various solutions for this common problem without succe ...

IE7 disregards the margin set in a div after a div that has been positioned absolutely

Within a container, I have two divs - the first one with absolute positioning. Strangely, in IE7, the second div doesn't seem to acknowledge the top margin. Padding works fine, but for visual consistency, I prefer using margin. The culprit appears to ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

Understanding the implementation of options within dataTables that have been initialized with an aaData JavaScript array

When initializing my datatable, I used an aaData object and specific options like so: $('#dataTable').dataTable(dataTableObj, { "bPaginate": false, "bLengthChange": false, "bFilter": true, "bSort": false, "bInfo": false, ...

enclosing the pre tag within a table cell

Despite using the latest Twitter Bootstrap, I am facing some issues with pre tags inside table cells. When a line is too long, it should create a horizontal scroll, but unfortunately, that does not happen. Check out this example without using the pre tag. ...

Blurry text and icons in Bootstrap 3

Does anyone else notice a strange display issue with Bootstrap 3 fonts and glyphicons? It seems like the bitmaps and fonts are appearing blurry on desktops when using Firefox and Chrome, but everything looks fine on mobile devices. I've attached an ex ...

Is there a way to filter out elements that are not visible from a jQuery selector?

I am currently working on a form that includes a checkbox for toggling a "nickname" field. My goal is to ensure that all fields are filled out before enabling a button on the page. The challenge I face is that some input fields are hidden from the user by ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

The PUT rest service does not function in AngularJS version 1.0.8

I am facing an issue with my AngularJS application that has a CRUD Rest service. While the Create, Read, and Delete methods are functioning properly, the PUT method is not working. I have searched on Stackoverflow and found similar problems with accepted s ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

Steps to insert a large image into a div while maintaining the size ratio

https://i.sstatic.net/WvBbF.png I'm struggling to add a logo to the right corner of this div The logo size is too big and it doesn't adjust properly to the existing div height and width Below is the code I've tried, but the image is ruini ...

Sign in and view SESSION data on the current page without any need to refresh the

My website currently features a login form at the top of each page for users to input their username and password. Once the submit button is clicked, I utilize jQuery AJAX method to send the data to login.php without refreshing the page. Here, the credenti ...

Extract reference value from an HTML element

Is there a way to access the ref prop from an HTML element using Testing Library React? My current code snippet is as follows: it('element container ref should be null if prop noSwipe is passed', () => { const onCloseMock = jest.fn() ...

Having trouble aligning my CSS form correctly

The issue is with the alignment of the second row of textbox elements under the "Add Equipment" section on this page: While organizing the code in Dreamweaver, the elements line up correctly. However, when viewed in Google Chrome, they shift to the second ...

Sending JSON data to Python CGI script

I've successfully set up Apache2 and got Python running without any issues. However, I'm facing a problem with two pages - one is a Python Page and the other is an HTML page with JQuery. Could someone guide me on how to correctly make my ajax p ...

Lazy Loading fails to deliver for Ajax Requests

I recently integrated lazy loading following David Walsh's advice (tip 1) and it initially worked perfectly. However, I encountered an issue when the images were filtered and reloaded with an ajax request. The website is built on Rails, and the images ...

Send the JSON file to the server by uploading it

Situation Currently, I'm dealing with a page comprising questions structured as shown below: sections:[{ section: 1, questions:[{ question: 1, attachment: [FormData Object] ... }, { question: 2, ...