zmerlin
zmerlin

Reputation: 35

Accordion - Change background color/image when toggling:

Issue with changing the background color/image when clicking on the arrow icon.

Looking to achieve two goals.

  1. When user clicks on arrow icon "to extend", the background needs to change to a color or an image. When user clicks on same arrow icon to "collapse" it needs to go back to default.

  2. Default - all collapsed and no green color shown.

Not concerned about the plus icon (left side) due to being removed later on.

Managed to change the color to green via styles when clicking on the arrow icon to extend, but by default the green is displayed, which it should not be, it should look like the other items that are not clicked.

I also tried to manipulate the js code to no avail.

Here it is in action for visual and further troubleshooting:

https://codepen.io/zmerlin/pen/gyxdPx

function toggleChevron(e) {
      $(e.target)
        .prev('.panel-heading')
        .find('i.indicator')
        .toggleClass('glyphicon-minus glyphicon-plus');
        //$('#accordion .panel-heading').css('background-color', 'green');
                $('#accordion .panel-heading').removeClass('highlight');
                $(e.target).prev('.panel-heading').addClass('highlight');
}
$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);

Upvotes: 0

Views: 600

Answers (1)

Entalpia
Entalpia

Reputation: 787

To get rid of the default green highlight on start, you should remove the highlight class from your first panel's .panel-heading.

Then, if you look carefully at your current code, you will see that regardless of the action you're taking, you always end up adding the highlight class:

$(e.target).prev('.panel-heading').addClass('highlight');

Since you would like to show the highlight when you open the panel, and hide it once the panel is closed, you should alter your code to the following:

function toggleChevron(e) {
    $(e.target)
      .prev('.panel-heading')
      .find('i.indicator')
      .toggleClass('glyphicon-minus glyphicon-plus');
    $('#accordion .panel-heading').removeClass('highlight');
    if (e.type === 'shown') {
      $(e.target).prev('.panel-heading').addClass('highlight');
    }
}

$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);

To explain it further - your toggle function is executed on both event types: shown and hidden. You can then use the if case to check if the user is opening or closing the tab, and add the highlight class only when necessary.

Upvotes: 1

Related Questions