kdskii kdskii - 1 year ago 86
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 Source

You could do it this way

// Toogle Left Sidebar

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

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


<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;