Fortytwo Fortytwo - 2 months ago 16
HTML Question

How to toggleoff/rehide div when it is trigged by onlick?

When I click on DIV 1, it shows the drop down. Now I want to hide the drop down when I click on default tab or click anywhere else on the page to toggle off the drop down menu. How I go about write the JavaScript code for this?

HTML

<div id="dropdown-container">
<div id="default-tab" onclick="toggleMenu()"><a href="#">1</a></div>
<ul id="dropdown">
<li ><a href="#"><span class="current-browse">2</span></a>
<ul class="dropdown-items">
<li class="dropdown-item"><a href="#">3</a></li>
<li class="dropdown-item""><a href="#">4</a></li>
</ul>
</li>
</ul>
</div>
</div>


Javascript

function toggleMenu() {
var dropDown = document.getElementById('dropdown');
if(dropdown.style.display == "block") {
dropdown.style.display = "none";
} else {
dropdown.style.display = "block";
}
}


CSS for dropdown has the display: none;

Answer

This article is an excellent explanation of the problem you are facing, and why the stopPropagation solution is a Bad Idea. Since you aren't using JQuery, what you want to do will look more like this:

document.onclick = function(event) {
  if (!event.target.closest('#dropdown-container')) {
    dropdown.style.display = "none";
  }
}

Drop that outside of your toggleMenu function and it should hide your menu whenever anything else on your page is clicked without creating unexpected behavior (bugs) for other libraries.