2
votes

at the moment i've code out like

$('.collapse').on('show.bs.collapse',function(){
   $('.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-menu-up');
});
$('.collapse').on('hide.bs.collapse',function(){
   $('.glyphicon-menu-up').removeClass('glyphicon-menu-up').addClass('glyphicon-plus');
});

and my HTML Code look like (for example)

<span class="glyphicon glyphicon-plus" data-toggle="collapse" 
      data-target="#a" aria-expanded="false" aria-controls="a"></span>
<div class="collapse" id="a"></div>
<span class="glyphicon glyphicon-plus" data-toggle="collapse" 
      data-target="#b" aria-expanded="false" aria-controls="b"></span>
<div class="collapse" id="b"></div>
<span class="glyphicon glyphicon-plus" data-toggle="collapse" 
      data-target="#c" aria-expanded="false" aria-controls="c"></span>
<div class="collapse" id="c"></div>
<span class="glyphicon glyphicon-plus" data-toggle="collapse" 
      data-target="#d" aria-expanded="false" aria-controls="d"></span>
<div class="collapse" id="d"></div>

The things that happening now is

  • when i click to call function or expand div all the span class change into "glyphicon-menu-up" (triggered by expending)

Things that i want to do is

  • When i click one of them to call function or expand div i need only one span class i've click to change the class

Optional

  • when i click another span (or to expand other div) the span/div i click before back to normal (not click) states while i'm using

    $('.collapse').click(function(e){
       e.stopPropagation();
    });
    

Change JS Only would be grateful

Because i don't want to change HTML code (in this case it's only example but in my whole project it's hard to change so i try to select that span by using collapse event of bootstrap)

Thanks

1

1 Answers

1
votes

You need to refer with current element using this when you are collapsing as below:

$('.collapse').on('show.bs.collapse',function(){
      $(this).prev('span').toggleClass('glyphicon-plus glyphicon-minus');
      //get the previous span of this element and toggle its above classes
}).on('hide.bs.collapse',function(){
      $(this).prev('span').toggleClass('glyphicon-plus glyphicon-minus');
      //get the previous span of this element and toggle its above classes
});

DEMO

Regarding your optional case, I hope you are expecting the below functionality:

$('.collapse').on('show.bs.collapse',function(){
      $('.collapse').not($(this)).removeClass('in');
      //hide all divs except this which are open by removing its `in` class
      $('.collapse').not($(this)).prev('span').addClass('glyphicon-plus').removeClass(' glyphicon-minus');
      //change all classes except the previous spans of this element back to normal
      $(this).prev('span').toggleClass('glyphicon-plus glyphicon-minus');
}).on('hide.bs.collapse',function(){
      $(this).prev('span').toggleClass('glyphicon-plus glyphicon-minus');
});

UPDATED DEMO