Others



Hide / Show Sidebar Using CSS and JavaScript


This example shows, how to create collapse sidebar using CSS and JavaScript. We have to show sidebar using 'showBar()' method and hide sidebar using 'hideBar()' method.

Demo

Example
<html>
  <head>
    <style>
      html,body{
        margin:0;
        padding:0;
      }
      .sidebar{
        position:relative;
        top:0;
        width:200px;
        height:100%;
        box-shadow:2px 2px 3px 3px #ccc;
        box-sizing:border-box;
        padding:20px 30px;
        background:white;
      }
      .sidebar .menu a{
        display:block;
        margin-bottom:10px;
        font-size:1.2rem;
        text-decoration:none;
        color:black;
      }
      .close-icon{
        position:absolute;
        right:15px;
        top:10px;
        text-decoration:none;
        font-size:1.4rem;
      }
      .open-icon{
        position:absolute;
        left:0px;
        top:10px;
        text-decoration:none;
        font-size:1.8rem;
        font-weight:800;
        padding:2px 5px;
        box-shadow:1px 1px 1px 1px #ccc;
      }
      .hide{
        transition:left 0.8s linear;
        left:-210px;
      }
      .show{
        transition:left 0.8s linear;
        left:0px;
      }
    </style>
  </head>
  <body>
    <a class='open-icon' href='#' onclick='showBar(event)'>&#8594;</a>
    <div class='sidebar show'>
      <a class='close-icon' href='#' onclick='hideBar(event)'>&#10006;</a>
      <div class='menu'>
        <a href='#'>Home</a>
        <a href='#'>Contact Us</a>
        <a href='#'>About Us</a>
      </div>
    </div>
    
    <script>
      function hideBar(e){
        e.preventDefault();
        var sidebar=document.querySelector(".sidebar");
        sidebar.classList.remove("show");
        sidebar.classList.add("hide");
      }
      function showBar(e){
        e.preventDefault();
        var sidebar=document.querySelector(".sidebar");
        sidebar.classList.remove("hide");
        sidebar.classList.add("show");
      }
    </script>
  </body>
</html>
Try it Yourself