Andy
Andy

Reputation: 179

HTML - Sidebar not closing when clicking outside of it

I have a sidebar that shows when an image is pressed. However, when I click outside of the sidebar, any area that is not the sidebar, it doesn't close. I tried looking it up but I didn't find a solution.

I am not so familiar with html so this might just be an easy fix.

var side = document.getElementById('mySidenav');
sideBarOpen = false;

function openNav() {
  document.getElementById("mySidenav").style.width = "300px";
  document.getElementById("arrow").style.transform = "rotate(90deg)";
  document.body.style.backgroundColor = "rgba(0,0,0,0.4)";

  sideBarOpen = true;
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("arrow").style.transform = "rotate(0deg)";
  document.body.style.backgroundColor = "white";
  sideBarOpen = false;
}

window.onclick = function(event) {
  if (sideBarOpen) {
    if (!event.target == side) {
      closeNav();
    }
  }
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a href="#"><img src="clubsIcon.svg" style="width: 30px; height: 30px;" align="center"></a>
  <a href="#"> &#8594;  <img src="srIcon.svg" style="width: 30px; height: 30px;" align="center"></a>
  <a href="#"><img src="cricketIcon.svg" style="width: 30px; height: 30px;" align="center"></a>
  <a href="#"><img src="fblaIcon.svg" style="width: 30px; height: 30px;" align="center"></a>
  <a href="#"><img src="roboticsIcon.svg" style="width: 30px; height: 30px;" align="center"></a>
</div>

<div style="font-size:30px;cursor:pointer;" onclick="openNav()">
  <img src="arrow.png" style="width: 20px; height: 20px;" id="arrow" class="arrowclass">
</div>

Upvotes: 1

Views: 692

Answers (1)

Leo Farmer
Leo Farmer

Reputation: 7910

The line in your code that is wrong is this:

if (!event.target == side) {

as !event.target will return a boolean which you are then comparing to an element. So you'll always get a negative response from this comparison.

it should be:

if (event.target !== side) {

Once that is sorted out, you will also have a logic problem as the opener button is positioned outside of the sidebar. You need to add a check that the window click event is not coming from the opener button in addition to your existing check that it isn't coming from the sidebar. See code changes below:

<div  id="openIcon" style="font-size:30px;cursor:pointer;" onclick="openNav()">
  <img src="arrow.png" style="width: 20px; height: 20px;" id="arrow" class="arrowclass">
</div>

javscript:

window.onclick = function(event) {
  if (sideBarOpen) {
    if (event.target !== side && event.target !== document.getElementById('openIcon')) {
      closeNav();
    }
  }
}

Upvotes: 2

Related Questions