kdskii kdskii - 2 months ago 9
Javascript Question

how to close sidebar by click inside body

hey i have an offcanva sidebar wich works pretty good. What i would to change is, that the users should close the sidebar by cklicking wherever they whant. For example inside the body.

At the moment is there a close button inside the sidebar which brings it back to default.

function openNav() {
document.getElementById("left-sidebar").style.width = "250px";
}

function closeNav() {
document.getElementById("left-sidebar").style.width = "0";
}


opens sidebar

<a href="#" onclick="openNav()"><i class="icon-menu"></i></a>


close sidebar

<a href="javascript:void(0)" class="closebtn" onclick="closeNav()"></a>

Answer

You could do it this way

// Toogle Left Sidebar

$('#open-pulse-sidebar').click(function() {
  $('.pulse-sidebar').toggleClass('active')
})

$(document).click(function(e) {
  var sidebar = $(".pulse-sidebar, #open-pulse-sidebar");
  if (!sidebar.is(e.target) && sidebar.has(e.target).length === 0) {
    sidebar.removeClass('active')
  }
});

html:

<a href="#" id="open-pulse-sidebar"><i class="icon-menu circle-icon"></i></a>

and the width could you do via css.

Fore example:

width: 19.24em;
Comments