Expand child ul on click of parent li
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 a ul on a click of my parent li, the 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 UL
, then if I click on level 2 LI
that has UL
and also close UL
level 1 LI
; I would like him to keep opening the baby UL
. How can I get this functionality?
source to share
http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/2/
$(".Downloadscontainer li").click(function (e) {
e.stopPropagation();
$(this).children('ul').toggle();
});
Notes:
- You don't need to
each
attach handlers to multiple elements in jQuery. - You just need to stop the propagation of the child click to the parent LI in the DOM
- As it
@George
suggests you better bind to anchor click.
Taking the anchor approach, I 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 one closest
LI
to the anchor being pushed, then drills down to the childUL
(rather than navigating throughnext
, which requires a known layout. -
preventDefault
will stop empty links in a bookmark (href="#"
in your example) from scrolling to the top of the page. If they were full links, they would stop navigating them, so you might need additional validation if you add links to pages.
For example, you can check if a link is an empty bookmark and allow other links to run:
http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/7/
$(".Downloadscontainer a").click(function (e) {
if ($(this).attr("href") == '#') {
e.preventDefault();
$(this).closest('li').children('ul').toggle();
}
});
This script has an external link to google as well as links #
.
source to share
How to bind an event handler to an anchor ?:
$(".Downloadscontainer li a").click(function (e) {
e.preventDefault();
$(this).next('ul').toggle();
});
- Remember, prevent the default action of your anchor from being redirected if it has a link.
-
.each()
Many methods for jQuery cycle is required, the binding event processing techniques, such as.click()
,.change()
,.keydown()
etc. included.
source to share
I tried this and it succeeds, you can use it
$(".main-menu li").click(function (e) {
e.stopPropagation();
$(this).children('ul').slideToggle().css("padding-left", "30px");
});
I've added some extra felts to fill - on the left of each ul child so we can understand / determine which one is expanding.
source to share