Question

I've seen this asked a few times, but I can't seem to find something that works for me. I think some of the answers in this forum or for older versions of bootstrap.

First I should state that I'm still learning js and not great at it, but here's my situation. I have an accordion style collapse that I'm trying to change the class on when the group is either open, or closed respectively. This way the icon I'm using will switch from an open to a closed icon.

Here's my markup:

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                    <span class="accordion-up"></span>title
                </a>
            </h4>
        </div>

        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                content
            </div>
        </div>
    </div>
</div>

Here's the css:

.accordion-up {
  background: url("images/accordion-up.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
  padding: 5px 20px;
}

.accordion-down {
  background: url("images/accordion-down.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
  padding: 5px 20px;
}

Here's my js:

$(document).ready(function(){    
  $('#accordion').on('shown', function () {
    $(".accordion-down").removeClass("accordion-down").addClass("accordion-up");
  });

  $('#accordion').on('hidden', function () {
    $(".accordion-up").removeClass("accordion-up").addClass("accordion-down");
  });
});

If anyone can help me figure out how to make these changes toggle, it would be greatly appreciated.

Thanks!

Was it helpful?

Solution

Your callback syntax is incorrect for Bootstrap 3.

$(document).ready(function(){    
  $('#accordion').on('shown.bs.collapse', function () {
    $(".accordion-down").removeClass("accordion-down").addClass("accordion-up");
  });

  $('#accordion').on('hidden.bs.collapse', function () {
    $(".accordion-up").removeClass("accordion-up").addClass("accordion-down");
  });
});

http://getbootstrap.com/javascript/#collapse-usage

Here's a simpler version combining events in a single function and toggling classes:

$(function() { // shorthand for document.ready
  $('#accordion').on('shown.bs.collapse hidden.bs.collapse', function () {
    $('.accordion-down, .accordion-up').toggleClass('accordion-down accordion-up');
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top