10

Is there a way how can I automatically collapse panel in bootstrap 3.0 on small device? I would like to achieve same effect as top navigation - so when screen is small only a toggle button shows on screen.

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116

2 Answers2

8

This is what I do.

$(document).ready(function(){
  if ($(window).width() <= 480){  
    $('.panel-collapse').removeClass('in');
  }
});

$(window).resize(function(){
  if ($(window).width() >= 480){  
    $('.panel-collapse').addClass('in');
  }
  if ($(window).width() <= 480){  
    $('.panel-collapse').removeClass('in');
  }
});
Ken Ratanachai S.
  • 3,307
  • 34
  • 43
  • I don't like doing it this way because you need to assume the breakpoint sizes. It's safer and more correct to determine the current breakpoint and determine what to do based on that (see my answer) – Scribblemacher Aug 31 '17 at 18:49
3

The currently accepted answer makes an assumption about the break point size being 480. Since the break points can be changed via Less or Sass, a better solution is to figure out the breakpoint in JavaScript.

Bootstrap (surprisingly) doesn't have a built-in utility for doing that, but you can make one yourself easily enough by adding some test divs and checking their visibility. Example below:

var isBreakpoint = function(viewport_size){
  return $('.device-' + viewport_size).is(':visible')
}

$(document).ready(function(){
  var test_divs = "<div class='device-xs visible-xs'></div>"
  test_divs = test_divs + "<div class='device-sm visible-sm'></div>"
  test_divs = test_divs + "<div class='device-md visible-md'></div>"
  test_divs = test_divs + "<div class='device-lg visible-lg'></div>"
  $("body").append(test_divs)

  if (isBreakpoint('xs'){
    $('.panel-collapse').removeClass('in');
  }
  else {
    $('.panel-collapse').addClass('in');
  }
})

Adapted from: How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Scribblemacher
  • 1,518
  • 1
  • 16
  • 31