I have a nav menu that acts like an accordian. When I click on a menu item the sub menu appears. When I click on another main menu that sub menu appears and all the other main menus collapse. This part is working.
I want to include switching the chevron icon from pointing right, to pointing down when the menu is expanded (clicked on), and at the same time, when all the other main menus are collapsed, change the chevron icon from down back to right on those, e.g. on all others except the one clicked on.
I’m almost there, just need help with the logic.
html
<ul class="sidebar-nav">
<li class="dropdown">
<a class="nav-link" href="javascript:void(0);" ><i class="bi bi-house-fill me-3 fs-3"></i>Home<i class="bi bi-chevron-right iChev"></i></a>
<ul class="sidenav-second-level" id="collapseHome">
<li><a href="#lastp">Another</a></li>
<li><a href="#firstp">Link</a></li>
</ul>
</li>
<li class="dropdown">
<a class="nav-link" href="javascript:void(0);"><i class="bi bi-ethernet me-3 fs-3"></i>Plugins<i class="bi bi-chevron-right iChev"></i></a>
<ul class="sidenav-second-level" id="collapsePlugins">
<li><a href="#lastp">Another</a></li>
<li><a href="#firstp">Link</a></li>
</ul>
</li>
jQuery
$(document).ready(function(){
$('li.dropdown').click(function () {
$('li.dropdown').not(this).find('ul').hide();
$(this).find('ul').toggle('slow');
if($(this).find('ul').is(":visible")){
$(this).find('.iChev').toggleClass("bi-chevron-right bi-chevron-down");
$('li.dropdown ').not(this).find('.iChev').toggleClass("bi-chevron-down bi-chevron-right");
}else{
$(this).find('.iChev').toggleClass("bi-chevron-down bi-chevron-right");
}
});
$("li.dropdown ul li a").click(function(e){
e.stopPropagation();
});
});
Thanks in advance for any help 🙂
3
Answers
You don’t need to
toggleClass
on otherli
as they will be hidden. Instead, you can always removebi-chevron-down
and addbi-chevron-right
.For current
li
,toggle
show/hide andtoggleClass
is sufficient. This way, with just one click, theul
will be displayed, accompanied bybi-chevron-down
, and with another click, it will hide, accompanied bybi-chevron-right
. So replace theclick
code with the following:I am assuming that you are using an icon which is by default facing the right direction and you want to make it face downwards rather than change the icon completely as it will not be efficient. So,
There are 2 efficient methods to do so-
First Method) You can define a id let’s say ‘facing-down’ and then add CSS property to that id as:
Now you can toggle this id to the icon whenever you toggle that accordion.
[Pro Tip: You can add
transition:0.5s
to give a smooth transition effect too]Second Method) You can use JS Property of –
Try this logic, worked on my side: