Pingbeat Pingbeat - 4 months ago 8
HTML Question

Bootstrap Navigation Javascript not working

my Javascript that is supposed to open the 2nd layer of my Navigation does not work and I dont know why it is not working. Am I overseeing something obvious? Its a bit warm in my office atm. :D

$('.submenu').click(function(e) {
e.preventDefault();
if ($(this).closest("ul .sub").hasClass("hide")) {
$(this).closest("ul .sub").removeClass('hide');
$(this).closest("ul sub").addClass('show');
}
else {
$(this).closest("ul sub").addClass('hide');
$(this).closest("ul sub").removeClass('show');
}
});


The HTML:

<nav class="navbar navbar-default navbar-fixed-top">
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse">
<div class="centering">
<ul class="nav navbar-nav">
<li><a class="navbar-brand" href="#"><img id="navlogo" alt="trlololol" src="gfx/Logo_Friedhof_Bildmarke-01.svg"></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown<span class="nav-img"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="submenu dropdown-toggle"><a href="#">Next menu level<span class="nav-img"></span></a></li>
<ul class="sub hide">
<li><a href="#">Blablabla</a></li>
<li><a href="#">Blablubla</a></li>
<li><a href="#">Blablibla</a></li>
</ul>
<li><a href="#">One link</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown32<span class="nav-img"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="submenu"><a href="#">Next menu level<span class="nav-img"></span></a></li>
<ul class="sub hide">
<li><a href="#">Blablabla</a></li>
<li><a href="#">Blablubla</a></li>
<li><a href="#">Blablibla</a></li>
</ul>

Answer

You should nest your ul inside of your li like this:

              <li class="submenu"><a href="#">Next menu level<span class="nav-img"></span></a>
                <ul class="sub hide">
                  <li><a href="#">Blablabla</a></li>
                  <li><a href="#">Blablubla</a></li>
                  <li><a href="#">Blablibla</a></li>
                </ul>
              </li>

Then you can do:

$('.submenu').click(function(e) {
    $(this).children('ul.sub').toggleClass('hide')
 });

fiddle: https://jsfiddle.net/hubkefw7/