Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I apply jQuery.click to first level items only?
    primarykey
    data
    text
    <p>I need to apply a jQuery.click to the first level items only. How do I do that?</p> <p>Here is my list:</p> <pre><code>&lt;ul id="adminMenu"&gt; &lt;li id="A"&gt; &lt;h3&gt;&lt;a href=""&gt;Item 1&lt;/a&gt;&lt;/h3&gt; &lt;/li&gt; &lt;li id="B"&gt; &lt;h3&gt;Item 2&lt;/h3&gt; &lt;ul style="display: block;"&gt; &lt;li id="a1"&gt; Sub Item 1 &lt;/li&gt; &lt;li id="a2"&gt; Sub Item 2 &lt;/li&gt; &lt;li id="a3"&gt; Sub Item 3 &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li id="C"&gt; &lt;h3&gt;Item 3&lt;/h3&gt; &lt;ul style="display: none;"&gt; &lt;li&gt; Sub Item 4 &lt;/li&gt; &lt;li&gt; Sub Item 5 &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And here is the jQuery</p> <pre><code>jQuery('#adminMenu &gt; li').click(function(){ alert('test'); }); </code></pre> <p><strong>UPDATE</strong><br /> The Alert should <strong>not</strong> fire when I click a Sub Menu item, only when I click list item A, B or C.</p> <p><strong>SOLUTION 1</strong> <br /> This is working code based on Marcels suggestion. </p> <pre><code> jQuery('#adminMenu &gt; li &gt; h3').click(function(e) { var activeUL = jQuery("#adminMenu &gt; li ul:visible"); var activeLI = jQuery("#adminMenu &gt; li ul:visible").parent('li:first'); var clicked = jQuery(this).parent('li:first'); // Close submenu activeUL.hide('fast'); // Open submenu if( activeLI.attr('id') != clicked.attr('id') ) clicked.children('ul').show('fast'); }); </code></pre> <p><strong>SOLUTION 2</strong> <br /> This is working code based on Eyelids suggestion. </p> <pre><code> jQuery('#adminMenu &gt; li').click(function(e) { var clicked = jQuery(e.target); // Ensure we're checking which list item is clicked, // other children should be allowed if(!clicked.is('li') &amp;&amp; clicked.parents('li').length &gt; 0) { // :first ensures we do not select higher level list items clicked = clicked.parents('li:first'); } // If clicked list item is a child of another list item, we'll exit here if(!clicked.is('#adminMenu &gt; li')) { return; } var activeUL = jQuery("#adminMenu &gt; li ul:visible"); var activeLI = jQuery("#adminMenu &gt; li ul:visible").parent('li:first'); // Close submenu activeUL.hide('fast'); // Open submenu if( activeLI.attr('id') != clicked.attr('id') ) clicked.children('ul').show('fast'); }); </code></pre> <p>Thanks guys! I would never have managed this without your help! :)</p>
    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