Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  106] [ 2]  / answers: 1 / hits: 23384  / 7 Years ago, mon, february 20, 2017, 12:00:00

I am implementing a ul and li list, from json data and with expand/collapse function.



The problem is that when trying the expand/collapse, all the subitems are expanding together, but i want only the clicked one to be collapsed/expanded;



Here is my code :



<html>
<head>
<script type=text/javascript src=//code.jquery.com/jquery-1.9.1.js></script>
<script src=//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js></script>
<style type=text/css>
ul li ul {
display: none;
}
a {
color: red;
}
</style>
<title></title>
</head>
<body>
<ul id=menu class=list>
</ul>
<script type=text/javascript>
$(window)
.load(
function() {
var JSON = {
menu : [ {
name : 'Title',
link : '#',
sub : [ {
name : 'Enclosure1',
link : '#',
sub : null
}, {
name : 'Enclosure2',
link : '#',
sub : null
}, {
name : 'Enclosure3',
link : '#',
sub : null
} ]
},{
name : 'Link',
link : '#',
sub : null
},{
name : 'Content',
link : '#',
sub : null
},{
name : 'Enclosures',
link : '#',
sub : [ {
name : 'Enclosure1',
link : '#',
sub : null
}, {
name : 'Enclosure2',
link : '#',
sub : null
}, {
name : 'Enclosure3',
link : '#',
sub : null
} ]
}, {
name : 'Authors',
link : '#',
sub : [ {
name : 'Author1',
link : '#',
sub : null
}, {
name : 'Author2',
link : '#',
sub : null
} ]
},{
name : 'Published At',
link : '#',
sub : null
}, {
name : 'Stream',
link : '#',
sub : [ {
name : 'STR1',
link : '#',
sub : null
}, {
name : 'STR2',
link : '#',
sub : null
} ]
} ]
}

$(function() {

function parseMenu(ul, menu) {
for (var i = 0; i < menu.length; i++) {
var li = $(ul).append(
'<li>'+ menu[i].name
+ '</li>');
if (menu[i].sub != null) {
var subul = $('<ul class=list></ul>');
$(li).append(subul);
parseMenu($(subul), menu[i].sub);
}
}
}

var menu = $('#menu');
parseMenu(menu, JSON.menu);
});
});//]]>​
</script>
<script type=text/javascript>$(document).on('click', '.list > li ', function () {
$(this).parent().children('ul').toggle();
})
</script>
</body>
</html>

More From » html

 Answers
1

In your script , change to toggle the next UL tag.



<script type=text/javascript>$(document).on('click', '.list > li ', function () {
$(this).next('ul').toggle();
})</script>


http://codepen.io/anon/pen/xgoapR



And to start with submenu collapsed, change



ul li ul {
display: none;
}


to



ul >  ul {
display: none;
}


EDIT:
Check a full working example with collapse, animation, and +/- toggle in
http://codepen.io/anon/pen/mWbLpm


[#58858] Saturday, February 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;