Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  17] [ 3]  / answers: 1 / hits: 8353  / 10 Years ago, fri, october 17, 2014, 12:00:00

I have the following structure:



<div class=Downloadscontainer>
<ul>
<li>level 1</li>
<li><a href=#>level 1</a>
<ul>
<li>level 2</li>
<li>level 2</li>
<li><a href=#>some page</a>
<ul>
<li>level 2</li>
<li>level 2</li>
</ul>
</li>
</ul>
</li>
</ul>




And i am trying to display ul on click of its parent li, following is my jquery



 $(document).ready(function () {
$(.Downloadscontainer ul li ul).css(display, none);
$(.Downloadscontainer li).each(function () {
$(this).click(function () {
if ($(this).children('ul').length > 0) {
$('.Downloadscontainer li ul').toggle();
}
});
});
});


So if I click on level 1 LI it displays the UL and then if I click on level 2 LI which have UL as well it close down the UL of level 1 LI; I would like it to keep opening the child UL. How can I obtain this functionality ?



link to fiddle


More From » jquery

 Answers
3

http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/2/



 $(.Downloadscontainer li).click(function (e) {
e.stopPropagation();
$(this).children('ul').toggle();
});


notes:




  • You do not need to each to attach handlers to multiple elements in jQuery.

  • You just need to stop the child click propagating to the parent LI in DOM

  • As @George suggests you may be better off attaching to the anchor click.



Taking the anchor approach I would suggest the following as DOM-change friendly:



http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/5/



 $(.Downloadscontainer a).click(function (e) {
e.preventDefault();
$(this).closest('li').children('ul').toggle();
});


Notes:




  • It finds the closest LI to the anchor clicked, then drills down to the child ULs (rather than navigate via next, which required a known arrangement.

  • preventDefault will stop blank bookmark links (href=# in your example) from scrolling to the top of the page. If they were full links they would stop them navigating, so you may need an additional check if you add page links.



e.g you can check if the link is a blank bookmark and allow other links to fire normally:



http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/7/



 $(.Downloadscontainer a).click(function (e) {
if ($(this).attr(href) == '#') {
e.preventDefault();
$(this).closest('li').children('ul').toggle();
}
});


This fiddle has an external link to Google, as well as the # links.


[#41832] Thursday, October 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;