How to close a javascript menu
<p>I'm creating pulldown menus that must be clicked on to open.  This code lets the user opening menus just fine. The only problem is I haven't figured out how to close the menus yet by clicking outside the menus.  I tried adding the "document.onclick" shown, but it takes effect even in the menus.  </p>

<p>I think I need to prevent document.onclick from being captured by other elements, but am not sure how to do this cross-platform.  Can someone please show me how?</p>

<pre><code>&lt;script type="text/javascript"&gt;
  var lastOpenedMenuId = null;

  function showMenu(menuId) {
    if (lastOpenedMenuId != null &amp;&amp; lastOpenedMenuId != menuId) {
      hideLastOpenedMenu();
    }
    setMenuVisibility(menuId, 'visible');
    lastOpenedMenuId = menuId;
  }
  function hideMenu(menuId) {
    setMenuVisibility(menuId, 'hidden');
  }
  function hideLastOpenedMenu() {
    if (lastOpenedMenuId != null) {
      hideMenu(lastOpenedMenuId);
    }
  }
  function setMenuVisibility(menuId, visibleOrHidden) {
    var menuElement = document.getElementById(menuId);
    menuElement.style.visibility = visibleOrHidden;
  }
  document.onclick = hideLastOpenedMenu;
&lt;/script&gt;

&lt;div onmousedown="showMenu('foodmenu')"&gt;&lt;a&gt;FOOD&lt;/a&gt;&lt;/div&gt;
&lt;div id="foodmenu" onmouseup="hideMenu('foodmenu');"&gt;
    &lt;a href="#meat"&gt;Meat&lt;/a&gt;
    &lt;A href="#tofu"&gt;Tofu&lt;/a&gt;
&lt;/div&gt;
</code></pre>

<p>Thanks in advance.</p>

<hr>

<p>I have made some progress and have reformulated the question here:
<a href="http://stackoverflow.com/questions/3076642/how-to-stop-onclick-event-in-div-from-propagating-to-the-document">http://stackoverflow.com/questions/3076642/how-to-stop-onclick-event-in-div-from-propagating-to-the-document</a></p>
