Fortytwo Fortytwo - 1 month ago 4x
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?


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


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

CSS for dropdown has the display: none;


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 (!'#dropdown-container')) { = "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.