Use Only Close Toggle To Close the Sidebar Not Menu Button


So i have a sidebar where in normal situation is hidden (using position: absolute; & left: -100%) so after the Menu button clicked on, it will get visible (left: 0;)but at the same time it get close using the Menu button which is not my preference, i want it to close only using the Close Button

Here are the codes:


<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Displaying Hidden Sidebar</title>
    <link rel="stylesheet" href="styles.css">

    <aside class="sidebar">
            <button id="close-menu" aria-label="Close menu">+</button>
            <button id="open-menu" aria-label="Open menu">Menu</button>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Work</a></li>
                <li><a href="#">Contact</a></li>
    <script src="main.js"></script>



body {
    margin: 0;

.sidebar {
    position: absolute;
    background-color: #000;
    height: 100%;
    left: -100%;
    transition: left 0.3s ease-in;

.sidebar--visible {
    left: 0;

.sidebar ul {
    list-style: none;
    margin: 0;
    padding: 72px;
    position: relative;

.sidebar li {
    margin: 12px 0;

.sidebar a {
    color: #000;
    text-decoration: none;
    font-size: 1.4rem;
    font-family: 'Dark mono', monospace;
    color: #fff;

.sidebar a:hover,
.sidebar a:focus {
    text-decoration: underline;
    /*outline: 0;*/

#open-menu {
    border: 2px solid #000;
    background: none;
    font-size: 1.4rem;
    font-family: 'Dank mono', monospace;
    padding: 6px 24px;
    cursor: pointer;
    position: fixed;
    right: 24px;
    top: 24px;

#close-menu {
    background: none;
    border: none;
    transform: rotate(45deg);
    font-size: 72px;
    font-family: 'Dank mono', monospace;
    color: #fff;
    cursor: pointer;
    position: absolute;
    right: 6px;
    top: -12px;
    z-index: 2;


const sidebar = document.querySelector('.sidebar')
const openMenu = document.querySelector('#open-menu')
const closeMenu = document.querySelector('#close-menu')

openMenu.addEventListener('click', toggleSidebarVisibility)
closeMenu.addEventListener('click', toggleSidebarVisibility)

function toggleSidebarVisibility() {

ok but you have event listeners on both on close and on open and they both do the same function. So to prevent it you must to constrain one. make it with if Example, if classList contains sidebar–visable, then work only close, and opposite

1 Like

So, i came up with 2 solutions, the first one is nice(I personally prefer the first one), the second one is a little bit nasty :grinning_face_with_smiling_eyes: but it does the trick :slightly_smiling_face: