How To Create a Collapsed Sidebar with JavaScript

In this article we can discuss about How To Create a Collapsed Sidebar with JavaScript.

How To Create a Collapsed Sidebar with JavaScript

In this we Can create collapsed sidebar with CSS and JavaScript. mostly we can use for mobile navigation menu.

Navigation is a critical part of UX design, but sometimes, there are so many navigation options that are things like mega menus simply aren’t functional. In those moments, it’s often easier to break up the navigational elements as to not overwhelm a user.

in that situation become quite apparent when using navigational links in your template’s sidebar, aside, or other secondary template element. A unique way to streamline, but still include all necessary links, in your sidebar navigation is to make your primary, top-level links expandable/collapsible. With this method, users can clearly get to the links and sections they need, and yet you preserve your design and prevent long lists from displaying by default.

<div id="mySidebar" class="sidebar">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>

<div id="main">
  <button class="openbtn" onclick="openNav()">☰ Open Sidebar</button> 


body {
  font-family: "Lato", sans-serif;

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;

.sidebar a:hover {
  color: #f1f1f1;

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;

.openbtn:hover {
  background-color: #444;

#main {
  transition: margin-left .5s;
  padding: 16px;

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
  .sidebar {padding-top: 15px;}
  .sidebar a {font-size: 18px;}


function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft= "0";

Note: If you want Sidebar full width to the devices “style.width=”100%”;” above JavaScript Code.

Also Read How to insert Checkbox inside Select dropdown

If you interested in the Entertainment genre please check this also

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *