Search code examples
bootstrap-4

Bootstrap4 Collapse toggle


I'm trying to style collapse toggle on it clicked and expect that there is a toggle class when collapse is show. But the actual logic in bootstrap4, for example:

<button data-toggle="collapse">Button</button> <div class="collapse">Collapse Content</div>

  1. first click, collapse will show and button classname will not be change.
  2. click again, a new classname collapsed added to button toggle.
  3. click again, classname collapsed will be removed from button toggle.

How can I style button toggle to different style when collased content is show?


Solution

  • http://getbootstrap.com/docs/4.1/components/collapse/

    $(document).ready(function(){
    
    $('#collapseExample').on('hide.bs.collapse', function () {
       $('#myBtn').removeClass('btn-success');
       $('#myBtn').addClass('btn-primary');
    });
    
    $('#collapseExample').on('show.bs.collapse	', function () {
       $('#myBtn').removeClass('btn-primary');
       $('#myBtn').addClass('btn-success');
    })
    
    });
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
    
    
     <button id="myBtn" class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
        Button 
      </button>
    
    <div class="collapse" id="collapseExample">
      <div class="card card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
      </div>
    </div>