Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter bootstrap: adding a class to the open accordion title

I am a jquery/javascript newbie. What I want to do is add a class to the open accordion title, and remove it when i open another.

heres the code:

<div class="accordion" data-collapse-type="manual" id="parent">
  <div class="accordion-group">
    <div class="accordion-heading">             
      <a class="accordion-toggle category" data-toggle="collapse" data-parent="#parent" href="#category1">Category 1
      </a>
    </div><!--/accordion-heading-->
    <div id="category1" class="accordion-body collapse">
      <ul class="accordion-inner unstyled">
        <li id="" class="sidelink"><a href="">Open Link 1</a></li>
        <li id="" class="sidelink"><a href="">Open Link 2</a></li>
        <li id="" class="sidelink"><a href="">Open Link 3</a></li>
      </ul>
    </div><!--/category1-->
  </div><!--/accordion-group-->
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle category" href="#Category2">Category 2</a>
    </div><!--/accordion-heading-->
  </div><!--/accordion-group-->
</div><!--/accordion-->

The scripts I have attached with the page are

<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.tools.min.js"></script>

So what I was looking for was to add the .active class to a.accordion-toggle whenever the menu is open (accordion style), and then have it go away once another is selected. I've looked at the documentation to bootstrap here, but it doesnt seem to help me out a lot (since I don't know what to do with the

$('#myCollapsible').on('hidden', function () { // do something… })

or where to place it) I've also tried the .addClass() jquery adder, but I could only get the javascript version document.getElementById("accordion-heading").className += " newClass"; to work (if I gave the accordion group title an ID, but in this case there will be multiple accordion groups) when I put the script right after the div layer.

like image 948
tgunnoe Avatar asked Jun 06 '12 17:06

tgunnoe


1 Answers

You can use the Collapse events for this.

$(function() {

    $('.accordion').on('show', function (e) {
         $(e.target).prev('.accordion-heading').find('.accordion-toggle').addClass('active');
    });

    $('.accordion').on('hide', function (e) {
        $(this).find('.accordion-toggle').not($(e.target)).removeClass('active');
    });

});​

Here's a JsFiddle http://jsfiddle.net/D2RLR/251/

like image 60
Michael D. Irizarry Avatar answered Oct 13 '22 06:10

Michael D. Irizarry