Home > Back-end >  How to close sidebar when clicking outside
How to close sidebar when clicking outside

Time:01-23

Hope someone advise,

How can I close the sidebar when clicking outside I already know the way of closing it while clicking a certain button

    //MOBILE MENU OPEN
    $(".ed-micon").on('click', function() {
        $(".ed-mm-inn").addClass("ed-mm-act");
    });

    //MOBILE MENU CLOSE
    $(".ed-mi-close").on('click', function() {
        $(".ed-mm-inn").removeClass("ed-mm-act");
    });

I tried to make it as below but the browser considered the open sidebar button enter image description here a part from the body

    $("body").on('click', function() {
        $(".ed-mm-inn").removeClass("ed-mm-act");
    });

I expect someone help. Thanks in advance.

CodePudding user response:

let sidebar = document.querySelector(".sidebar")

document.querySelector('.open').onclick = e => {
  sidebar.style.display = "block"
  e.stopPropagation()
}

document.body.addEventListener("click", e => sidebar.style.display = "none")
.sidebar {
  background: coral;
  position: fixed;
  top: 0;
  left: 0;
  width: 40%;
  height: 100vh;
  animation-name: sider;
  animation-duration: 800ms;
  transform-origin: top left;
}

* {
  text-align: right;
}

@keyframes sider {
  from {
    transform: scaleX(0.0);
    opacity: 0.7;
    border-radius: 0 50% 50% 0;
  }
  to {
    transform: scaleX(1.0);
    opacity: 1.0;
    border-radius: 0;
  }
}
<button >open</button>
<div >sidebar</div>
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla
<br> bla bla

You can add an event listener to the body of the document. Be careful with how you'll handle it in your sidebar too as clicks here will trigger body's click function too

  • Related