How to Create a Collapsible Sidebar Menu

A collapsible sidebar menu is a type of navigation menu that can be hidden or displayed with a button.

It’s a great way to organize the content of a website and make it easy to access.

A collapsible sidebar menu can be implemented using JavaScript, CSS and HTML.

In this tutorial, we’ll show you how to create a simple and elegant collapsible sidebar menu for a website.


HTML Structure

Let’s start by creating the HTML structure for the sidebar menu.

The following code will create a container with a button that can be used to toggle the menu.

<div class="sidebar">
  <button class="sidebar-toggle">Toggle Sidebar</button>
  <nav class="sidebar-nav">
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</div>

CSS Styles

The next step is to add the styles for the sidebar menu.

The following code will create the basic styles for the sidebar, toggle button and the navigation menu.

.sidebar {
  position: fixed;
  top: 0;
  left: -200px;
  height: 100%;
  width: 200px;
  background-color: #333;
  transition: all 0.3s ease-in-out;
}

.sidebar-toggle {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: #fff;
  border: none;
  color: #333;
  padding: 10px 15px;
  cursor: pointer;
}

.sidebar-nav {
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

.sidebar-nav li {
  display: block;
  margin: 0;
  padding: 0;
}

.sidebar-nav a {
  display: block;
  padding: 10px 15px;
  color: #fff;
  text-decoration: none;
}

JavaScript Function

The final step is to add the JavaScript function that will toggle the sidebar menu.

The following code will hide or show the sidebar when the toggle button is clicked.

const toggleButton = document.querySelector('.sidebar-toggle');
const sidebar = document.querySelector('.sidebar');

toggleButton.addEventListener('click', function() {
if (sidebar.style.left === '-200px') {
sidebar.style.left = '0';
} else {
sidebar.style.left = '-200px';
}
});

Conclusion

In this article, we’ve shown you how to create a simple and elegant collapsible sidebar menu for a website.

By following the steps outlined in this article, you can easily add a collapsible sidebar menu to your website.