Bootstrap Tutorial - Collapse sidebar programatically








The following code shows how to collapse sidebar programatically.

Example

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.0.2.js'></script>
<link rel="stylesheet" type="text/css"
  href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css"
  href="http://getbootstrap.com/dist/css/bootstrap.css">
<script type='text/javascript'
  src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script type='text/javascript'>
$(window).load(function(){<!--  ww w. j  av  a  2 s  . c  o  m-->
$("#ToggleNavScript").click(function() {
    $('.navbar-collapse').collapse('toggle');
});
});
</script>
</head>
<body>
  <div class="navbar navbar-inverse ">
    <div class="container">
      <!-- Header -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse"
          data-target=".navbar-collapse">
          <span class="icon-bar"></span> <span class="icon-bar"></span> <span
            class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Bootstrap 3.0 Skeleton</a>
      </div>
      <!-- Navbar Links -->
      <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#about">About</a></li>
          <li><a href="#contact">Contact</a></li>
        </ul>
      </div>
    </div>
  </div>
  <button id="ToggleNavAttr" class="btn btn-primary btn-lg"
    data-toggle="collapse" data-target=".navbar-collapse">
    Toggle Nav Attribute</button>
  <button id="ToggleNavScript" class="btn btn-primary btn-lg">
    Toggle Nav JavaScript</button>
  <!-- Post Info -->
  <div
    style='position: fixed; bottom: 0; left: 0; background: lightgray; width: 100%;'>
    About this SO Question: <a
      href='http://stackoverflow.com/q/24531937/1366033'>Collapse
      sidebar programatically</a><br /> Fork This Skeleton Here: <a
      href='http://jsfiddle.net/KyleMit/kcpma/'>Bootstrap 3.0 Skeleton</a><br />
    <div>
</body>
</html>

Click to view the demo