List of hidden lists
I want to hide all ul parents from a span with a class "ul-menu"
, but the code I am writing only hides the first unclosed ul.
I want to hide every single ul menu from the span parent on page load, but that only hides ul number 1, I have checked that and if I remove "ul-menu"
from the range from ul number 1 and then ul number 2 is hidden, but I want to hide each of them. I tried with every function but it didn't help. Or can I hide the ul in a hidden top ul or something?
$('.ul-menu').on("click", function() {
var t = $(this);
t.parent().find('ul').toggle();
if (t.hasClass('glyphicon-chevron-down')) {
t.removeClass('glyphicon-chevron-down');
t.addClass('glyphicon-chevron-right');
} else {
t.addClass('glyphicon-chevron-down');
t.removeClass('glyphicon-chevron-right');
}
});
//Hiding function
$(document).ready(function() {
$('.ul-menu').parent().find('ul').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-menu well" id="pages">
<header>Sites</header>
<ul id="starter">
<li>
<span class="glyphicon glyphicon-record"></span>
<a href="?page=pages/About">About</a>
</li>
<li>
<span class="glyphicon ul-menu glyphicon-chevron-down"></span>
<a href="?page=pages/courses">Courses</a>
<ul>
<!-- Ul to hide number 1 -->
<li>
<span class="glyphicon ul-menu glyphicon-chevron-down"></span>
<a href="?page=pages/courses/topic_1">Topic 1</a>
<ul>
<!-- Ul to hide number 2 -->
<li>
<span class="glyphicon glyphicon-record"></span>
<a href="?page=pages/courses/topic_1/sub_topic_1">Sub Topic 1</a>
</li>
</ul>
</li>
<li>
<span class="glyphicon glyphicon-record"></span>
<a href="?page=pages/courses/topic_2">Topic 2</a>
</li>
</ul>
</li>
<li>
<span class="glyphicon glyphicon-record"></span>
<a href="?page=pages/main">Main</a>
</li>
</ul>
</div>
<!-- Menu-->
You should only target the sibling element ul
$('.ul-menu').on("click", function () {
var t = $(this);
t.nextAll('ul').toggle();
t.toggleClass('glyphicon-chevron-down glyphicon-chevron-right')
});
Demo: Fiddle
I believe your problem is in your display.
t.parent().find('ul').toggle();
This will find all the ul children and switch them. To find the nearest ones immediately, search for "> ul".