Show a different icon when the container is open compared to when it is closed using jQuery and Bootstrap

Upon page load, I am looking to have an accordion displayed with an open state, showing a minus icon. When the accordion is closed, the icon should change to a plus.

Check out this example on fiddle

$('div.accordion-body').on('shown', function () {
    $(this).parent("div").find(".icon-plus")
                         .removeClass("icon-plus")
                         .addClass("icon-minus");
});

$('div.accordion-body').on('hidden', function () {
    $(this).parent("div").find(".icon-minus")
                         .removeClass("icon-minus")
                         .addClass("icon-plus");
});

Is there a way to set the default icon for an open accordion to be a minus?

Answer №1

Instead of complicating things, there are simpler methods to achieve the same result as the existing solutions. Using CSS alone can eliminate the need to manipulate DOM elements dynamically.

You can achieve the desired effect by adding the following CSS (taken from show collapse state with Chevron icon):

.accordion-heading a:after {
    font-family: 'Glyphicons Halflings';
    content: "\2212"; /* Plus */   
    float: right; 
    color: grey; 
}
.accordion-heading a.collapsed:after {
    content: "\2b";  /* Minus */
}

This CSS code will automatically generate an icon and toggle it based on whether the anchor element has the collapsed class, eliminating the need for additional icon elements.

View Demo in jsFiddle


If you prefer not to use pseudo-selectors, another approach is to include both icons and then adjust their visibility as necessary:

Title One
<i class="icon-plus"></i>
<i class="icon-minus"></i>
.accordion-heading .icon-plus { display: none; }
.accordion-heading .icon-minus { display: block; }
.accordion-heading .collapsed .icon-plus { display: block; }
.accordion-heading .collapsed .icon-minus { display: none; }

View Demo in jsFiddle

Answer №2

If you check out the live demonstration where I customized your Fiddle to demonstrate its functionality.

function toggleChevron(e) {
    jQuery(e.target)
    .prev('.accordion-heading')
    .find("i")
    .toggleClass('icon-plus icon-minus');
}
jQuery('#comuniArchivos').on('hidden.bs.collapse', toggleChevron);
jQuery('#comuniArchivos').on('shown.bs.collapse', toggleChevron);

jQuery('.panel-default').on('show.bs.collapse', function() {
    jQuery(this).addClass('active');
});

jQuery('.panel-default').on('hide.bs.collapse', function() {
    jQuery(this).removeClass('active');
});

The initial toggle in your HTML should have a class of icon-minus since it is expanded by default.

Answer №3

Check out this code demo showcasing two simple functions that work flawlessly. You're definitely heading in the right direction:

$('#expandSection').on('show.bs.collapse',function() {
    $(".arrow").addClass('glyphicon-minus')
              .removeClass('glyphicon-plus');
});

$('#expandSection').on('hide.bs.collapse',function() {
    $(".arrow").addClass('glyphicon-plus')
              .removeClass('glyphicon-minus');
});

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

Putting a link on a button exclusively

Currently, I am utilizing Bootstrap 5 to develop a website. One of the pages features a header that consists of an image with text and a button overlay. The intended functionality is for users to be redirected to another site when clicking on the button. ...

Decreasing the height of a div that wraps a slider

Currently, I am using a slider and would like to showcase its functionality. Here is the demo link: I have tried wrapping this slider in a div element, but it unexpectedly decreases the height to 125px from the original 100%. Here is the original code: ...

Transform an array into a string with spaces in between each value by combining the elements

I have a complex select input on my website. By using jQuery, I can easily extract the selected values of all child option elements like this: $("#select").val(); This action returns an array as demonstrated below: ["Hello", "Test", "Multiple Words"] N ...

What is the best way to place text alongside a shape?

I'm attempting to place text beside the circular shape. HTML <div class="row"> <div class="col-sm-2"> <span><div class="circle"></div></span><p>available</p> </div> </div> C ...

Utilize CSS to create a visual buffer at the bottom of the header

I'm having trouble creating a gap between the bottom of "headermenu" and the top of "list". No matter what values I use for margin-bottom or padding-bottom, the table won't budge. I could try adding margin-top to the table, but I would prefer to ...

Issues with label tags not functioning properly on modal windows

I'm attempting to add label tags to my modal window in order to create a login form, but they're not appearing. You can view the issue on this fiddle Here's my jQuery code: $(document).ready(function () { var activeWindow; $(' ...

Is it possible to make a DIV adjust its size automatically when the browser is resized?

Greetings! Here's my initial query, with more to follow. I've encountered an issue where a div on my page is set to 70% of the screen, but upon resizing the browser to a smaller size, some content within the div extends past the bottom of the pa ...

Animating margins and padding using CSS transitions can result in a choppy and inconsistent animation effect

On my personal website, I have implemented the CSS3 Transition property on the top navigation to create an animation effect on an element with a border. This effect causes the border to swell when hovered over. Here is the relevant markup: <nav> ...

How to easily remove margin in a Bootstrap alert component

I'm having difficulty removing margins within a bootstrap alert component and I can't figure out why! https://codepen.io/weellydooh/pen/MWKKoqg <div class="alert alert-primary" role="alert"> <p>A simple primary alert—check it ...

The functionality of JQuery is not effective when trying to retrieve a radio button value within a partial view

Trying to extract a value from a radio button to toggle another component in a modal popup. I attempted to accomplish this by including JQuery code in a partial view within the modal popup, but unfortunately, it didn't work as expected. Interestingl ...

Expand the capabilities of a jQuery plugin by incorporating new functions or modifying existing ones

I have a task to enhance the functionality of a jQuery Plugin (https://github.com/idiot/unslider) by adding another public method. (function(){ // Store a reference to the original remove method. var originalMethod = $.fn.unslider; // Define a ...

Adjust the text size of Twitter Bootstrap on mobile screens

I recently started using Twitter Bootstrap. I am currently hiding certain <tr> elements on phone screens by utilizing the class="hidden-phone". However, I am now looking to resize the displayed text to better fit the screen. Is there a way to adjus ...

Excessive content in Bootstrap Table

I am currently facing an issue with two tables placed side by side using the Bootstrap grid system. While the tables are dynamic and visually appealing, I encounter a problem when adding lengthy strings dynamically. The overflow of text within the table ca ...

I am having trouble viewing my icons properly displayed in front of my buttons in HTML and CSS

I've been working on creating a background that, when hovered over, reveals 2 buttons with different icons on them. I'm trying to change the color of these icons from black to white using CSS. However, I'm facing an issue where I can't ...

What could be the reason for Jquery and Ajax not functioning correctly?

In this snippet, a counter is supposed to appear when there are rows with the status set to unread. Additionally, when the user clicks on an icon <i class="fas fa-bell"></i>, the row's status is expected to be updated to read. However, th ...

Determining Adjacency of <li> Elements Using jQuery Sortable() and Class Comparison

I have created a custom display builder specifically for outdoor power equipment dealers. This tool allows them to easily add, remove, and rearrange different product display sections according to their preferences. To achieve this functionality, I utilize ...

Trouble retrieving element height with jQuery .load() function

Running into an issue with my script that utilizes jQuery .load() to load content onto a page. The content loads fine, and the animation for it (using class "hidden") is working smoothly. However, I'm encountering a problem where the wrapping containe ...

Incorporate Extra Personalized Characteristics into Template (Slightly)

I'm interested in including additional attributes when using data-sly-call Here is the template: <template data-sly-template.button="${ @ model}"> <button data-info="Body" class="${model.moreClass}&qu ...

Fixed columns with horizontal scrolling to prevent Datatables columns from overlapping

I'm facing an issue with my data table created using datatables. I need to fix the first two columns, but when I do so, the other two columns overlap them while scrolling horizontally. If I remove the fixed columns, the scrolling works correctly witho ...

The Datatable fails to render the JSON data

Currently, I am dynamically binding a DataTable from a JSON URL and also generating headers dynamically. However, I am facing some issues in passing the JSON data to aaData in the DataTable. Can you please take a look at my code snippet below and provide m ...