Reputation: 25
I try to use JQuery to highlight the current main menupoint. It works clicking the main menu points, but not working in case of clicking on a sub menu point. Main menu points are always visible and submenu points are hidden with css. The 'li' tags of the main menu points always have the class dropdown and the others do not, so with the closest() method I would like to select the nearest 'a' ancestor (including itself as well) of the clicked menu point that has a parent 'li' with class dropdown. I tried to use the following JQuery code to do so, but somehow it is not working in case of clicking on a submenu point and I have no idea why. Any help would be appriciated.
JQuery:
$(document).ready(function(){
$("li a").click(function(){
$("li a.active").removeClass("active");
$(this).closest("li.dropdown a").addClass("active");
});
});
HTML:
<ul>
<li class="dropdown"><a class="active" href="#home"><i class="fa fa-home"></i></a></li>
<li class="dropdown"><a href="#">Menüpont 1</a>
<ul class="dropdown-content">
<li><a href="#menu11">Menüpont 1.1</a></li>
<li><a href="#menu12">Menüpont 1.2</a></li>
<li><a href="#menu13">Menüpont 1.3</a></li>
<li><a href="#menu14">Menüpont 1.4</a></li>
</ul>
</li>
<li class="dropdown"><a href="#">Menüpont 2</a>
<ul class="dropdown-content">
<li class="sub-dropdown"><a href="#">Menüpont 2.1<i class="fa fa-caret-right" aria-hidden="true"></i></a>
<ul class="sub-dropdown-content">
<li><a href="#menu211">Menüpont 2.1.1</a></li>
<li><a href="#">Menüpont 2.1.2</a></li>
<li><a href="#">Menüpont 2.1.3</a></li>
</ul>
</li>
<li><a href="#">Menüpont 2.2</a></li>
<li><a href="#">Menüpont 2.3</a></li>
<li><a href="#">Menüpont 2.4</a></li>
<li><a href="#">Menüpont 2.5</a></li>
<li><a href="#">Menüpont 2.6</a></li>
<li><a href="#">Menüpont 2.7</a></li>
</ul>
</li>
<li class="dropdown"><a href="#">Menüpont 3</a></li>
<li class="dropdown"><a href="#">Menüpont 4</a></li>
<li class="dropdown"><a href="#">Menüpont 5</a></li>
</ul>
Upvotes: 0
Views: 248
Reputation: 745
You trying get element by selector li.dropdown a
, but parent elements of you links is li
and ul.dropdown
.
If you want get all links in this menu, use this code
$(this).closest('.dropdown').find('li > a')
Upvotes: 1
Reputation: 25
I have just found the solution :)
$(document).ready(function(){
$("li a").click(function(){
$("li a.active").removeClass("active");
$(this).closest(".dropdown").children("a").addClass("active");
});
});
Upvotes: 0