0

When I click outside the dropdown menu then dropdown menu must close. How can I close the dropdown menu? Here is my code:

<div class="pull-right srch-box">
     <button onclick="search_function()" class="dropbtn"><i class="fa fa-search" aria-hidden="true"></i></button>
     <div id="myDropdown" class="dropdown-content">
          <form>
              <div class="input-group search-box form-group">
                 <input type="text" id="search" class="form-control" placeholder="Search here...">
                 <button type="button" class="btn btn-primary ">Search</i></button>
              </div>
          </form>
     </div>
</div>

js script for the open dropdown menu:

function search_function() {
    document.getElementById("myDropdown").classList.toggle("show");
}
 

What would be the js script to close the dropdown menu?

lime
  • 801
  • 8
  • 21
  • Does this answer your question? [jquery drop down menu closing by clicking outside](https://stackoverflow.com/questions/6463486/jquery-drop-down-menu-closing-by-clicking-outside) – AKNair Sep 24 '20 at 16:29

1 Answers1

0

Try something like this:

const dropdown = document.getElementById("myDropdown");

window.addEventListener('click', e => e.target !== dropdown ? dropdown.classList.remove('show') : false);

Basicly it puts an event on the entire window... and if you click on something that it isn't the dropdown will remove the show class

Stefan Dobre
  • 138
  • 6