Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After playing around in JsFiddle for a while I've come up with some code that does what you want, I've tried to change as little of the existing code as possible.</p> <pre><code>$(document).ready(function() { /* for keeping track of what's "open" */ var activeClass = 'dropdown-active', focusFired = false, showingDropdown, showingMenu, showingParent; /* hides the current menu */ var hideMenu = function() { if (showingDropdown) { showingDropdown.removeClass(activeClass); showingDropdown = null; showingMenu.hide(); } }; /* recurse through dropdown menus */ $('.dropdown').each(function() { /* track elements: menu, parent */ var dropdown = $(this); var menu = dropdown.next('div.dropdown-menu'), parent = dropdown.parent(); /* function that shows THIS menu */ var showMenu = function() { hideMenu(); showingDropdown = dropdown.addClass('dropdown-active'); showingMenu = menu.show(); showingParent = parent; }; /* function to toggle menu when clicked */ dropdown.bind('click', function(e) { console.log('Click fired'); if (e) e.stopPropagation(); if (e) e.preventDefault(); if(showingDropdown == dropdown &amp;&amp; !focusFired) { hideMenu(); } else { showMenu(); } focusFired = false; }); /* function to show menu when someone tabs to the box */ dropdown.bind('focus', function() { focusFired = true; showMenu(); }); }); /* hide when clicked outside */ $(document.body).bind('click', function(e) { if (showingParent) { var parentElement = showingParent[0]; if (!$.contains(parentElement, e.target) || !parentElement == e.target) { hideMenu(); } } }); }); </code></pre> <p>There are some things that are non-obvious at first, when you click into an element a focus event fires and a click event fires, since focus shows the menu you can't just check the state there because it will show and quickly hide the menu. That's why I added a focusFired flag that the click event checks before hiding.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload