XiLab XiLab - 1 year ago 167
Javascript Question

Sidebar Closes onclick only when click outside of it

I've a button/link which opens my sidebar, calling the relative function

. It's something like

<a id="menu-toggle" href="javascript:void(0);" onclick="event.stopPropagation(); opensidebar();" type="button">
<i class="sprite-t-toggle-side"></i>

which calls this function

function opensidebar() {
var $menu = $("#sidebar-wrapper");

and closes on document click like


It works but the problem is that the sidebar closes even if I click inside it. I'd like to keep it open because I have dropdown menus there.
How can I achieve it? Thanks.

Answer Source

You can do it like this

$('#open').click(function() {

$(document).click(function(e) {
  var sidebar = $(".sidebar, #open");
  if (!sidebar.is(e.target) && sidebar.has(e.target).length === 0) {
body, html {
  margin: 0;
  padding: 0;
.sidebar {
  transform: translateX(-120%);
  display: inline-block;
  height: 100vh;
  background: lightblue;
  transition: all 0.3s ease-in;
  width: 200px;
.active {
  transform: translateX(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">Sidebar</div>
<button id="open">Toggle</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download