Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap data toggle collapse only on small device

How can you use Bootstraps collapse function so that it only applies on mobile device without duplication code i.e I know how to acheive it using the visible and hidden classes but I'm looking for a more elegant solution where I don't have to duplicate the code.

currently the following will apply the toggle on all screen sizes:

 <a class="btn btn-primary" role="button" data-toggle="collapse" href="#1" aria-expanded="false" aria-controls="1">
      Link with href
    </a>

    <div class="collapse" id="1">

    </div>

 <a class="btn btn-primary" role="button" data-toggle="collapse" href="#2" aria-expanded="false" aria-controls="2">
      Link with href
    </a>

    <div class="collapse" id="2">

    </div>

 <a class="btn btn-primary" role="button" data-toggle="collapse" href="#3" aria-expanded="false" aria-controls="3">
      Link with href
    </a>

    <div class="collapse" id="3">

    </div>
like image 410
adam78 Avatar asked Sep 07 '26 23:09

adam78


1 Answers

you can do it based on window size. If it's less than 767px you can add data-toggle attribute with JavaScript.

Demo: https://jsfiddle.net/t1etnj5w/4/

$(document).ready(function(){
   console.log($(window).width());
   if ($(window).width() < 767) {
     $('.collapse-div').each(function(){
       $(this).attr('data-toggle','collapse'); 
     })
   }
})
like image 118
ItzMe_Ezhil Avatar answered Sep 10 '26 16:09

ItzMe_Ezhil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!