Note that there are some explanatory texts on larger screens.

plurals
  1. POHide dynamically created menu on click anywhere on page jquery
    primarykey
    data
    text
    <p>I have some dynamically created menus on a page that need to hide whenever the user clicks anywhere on the page. This needs to work if the user clicks the menu, or tries to open another menu. </p> <p>I also want the event handler to unbind itself when done hiding. I've found a solution using <code>document.on()</code> one <code>one()</code> but would really like to restrict the <code>document</code> handler to something further down the DOM. Problem is that it breaks my code. </p> <p>Any help with an elegant solution appreciated.</p> <p>The main reason I want to do this is to be able to prevent <code>event propagation</code> such as in:</p> <p><a href="http://jsfiddle.net/QsggA/8/" rel="nofollow"><strong>Failing propagation DEMO</strong></a> </p> <p><a href="http://jsfiddle.net/QsggA/9/" rel="nofollow"><strong>Succeeding propagation, failing <code>one()</code> clickhandler DEMO</strong></a> </p> <p><strong>Javascript</strong></p> <pre><code>// I want to change "document" to ".menus" here $(document).on("click", ".displayMenu", function(e) { var $menu = $(this).siblings(".menu"); $(document).one("click", function(e2) { if (e.target!=e2.target) $menu.hide(); }); $menu.toggle(); });​ </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class="menus"&gt; &lt;div&gt; &lt;div class="displayMenu"&gt;Show menu 1&lt;/div&gt; &lt;div class="menu"&gt;menu 1&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div class="displayMenu"&gt;Show menu 2&lt;/div&gt; &lt;div class="menu"&gt;menu 2&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;​ </code></pre>
    singulars
    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.
 

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