I need to apply jQuery.click only to first level elements. How to do it?
Here is my list:
<ul id="adminMenu">
<li id="A">
<h3><a href="">Item 1</a></h3>
</li>
<li id="B">
<h3>Item 2</h3>
<ul style="display: block;">
<li id="a1"> Sub Item 1 </li>
<li id="a2"> Sub Item 2 </li>
<li id="a3"> Sub Item 3 </li>
</ul>
</li>
<li id="C">
<h3>Item 3</h3>
<ul style="display: none;">
<li> Sub Item 4 </li>
<li> Sub Item 5 </li>
</ul>
</li>
</ul>
And here is jQuery
jQuery('#adminMenu > li').click(function(){
alert('test');
});
UPDATE The
warning should not be when I click on a submenu item, only when I click on list items A, B or C.
SOLUTION 1
This is working code based on the Marxels proposal.
jQuery('#adminMenu > li > h3').click(function(e) {
var activeUL = jQuery("#adminMenu > li ul:visible");
var activeLI = jQuery("#adminMenu > li ul:visible").parent('li:first');
var clicked = jQuery(this).parent('li:first');
activeUL.hide('fast');
if( activeLI.attr('id') != clicked.attr('id') )
clicked.children('ul').show('fast');
});
SOLUTION 2
This is a working code based on the proposal of the Century.
jQuery('#adminMenu > li').click(function(e) {
var clicked = jQuery(e.target);
if(!clicked.is('li') && clicked.parents('li').length > 0) {
clicked = clicked.parents('li:first');
}
if(!clicked.is('#adminMenu > li')) {
return;
}
var activeUL = jQuery("#adminMenu > li ul:visible");
var activeLI = jQuery("#adminMenu > li ul:visible").parent('li:first');
activeUL.hide('fast');
if( activeLI.attr('id') != clicked.attr('id') )
clicked.children('ul').show('fast');
});
Thanks guys! I would never have managed this without your help! :)
source
share