Shehab Mahmud
Shehab Mahmud

Reputation: 13

jQuery Remove class after clicking outside the div

How can Remove class after clicking outside the div. the following code isn't working. please help me. thanks...

<script> 
$(document).ready(function(){
    $(".toggles-menu").click(function(){
        $(".main-nav").slideToggle("200");
    });
});

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.toggles-menu')) {
    var mytoggles = document.getElementByClassName("main-nav");
      if (mytoggles.classList.contains('main-nav')) {
       mytoggles.classList.close('main-nav');
      }
  }
}
</script>

Upvotes: 0

Views: 478

Answers (1)

user10047017
user10047017

Reputation:

First, it's document.getElementsByClassName and that returns an array, so you need to use [0] to get the first element of that class.

$(document).ready(function(){
    $(".toggles-menu").click(function(){
        $(".main-nav").slideToggle("200");
    });
});

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.toggles-menu')) {
    var mytoggles = document.getElementsByClassName("main-nav")[0];
      if (mytoggles.classList.contains('main-nav')) {
       mytoggles.style.display="none";
      }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=".toggles-menu" style="border: 1px solid black">Menu</div>
<div class="main-nav">Main-nav div</div>

Upvotes: 1

Related Questions