My attempt to create a code that toggles a drop-down menu on every click and closes any other open menus is not working as expected. The menu doesn't close upon clicking it again.
$(document).ready(function(){
"use strict";
$(".dropdown").hide();
$("#smpg-cat-list li span").click(function() {
$(".dropdown").hide();
$("#smpg-cat-list li span").html('<i class="fa fa-plus" aria-hidden="true"></i>');
if( $(this).next('.dropdown').css('display') == 'none' ){
$(this).next('.dropdown').show();
$(this).html('<i class="fa fa-minus" aria-hidden="true"></i>');
}else{
$(this).next('.dropdown').hide();
$(this).html('<i class="fa fa-plus" aria-hidden="true"></i>');
}
});
});
I intend for the code to:
- Hide all instances of the class .dropdown.
- When #smpg-cat-list li span is clicked, close any open menus.
- Change the hidden elements' HTML to display a plus icon.
- Determine if the next .dropdown element has a display of none.
- If true, display the element and change the icon to minus.
- If false, hide the element and change the icon to plus.
The issue remains where the element shows but does not hide when clicked again.
HTML
<ul id="smpg-cat-list">
<li><a href="/web-design/">Web Design</a>
</li>
<li><a href="/robots/">Robots</a></li>
<li>
<a href="/programming/">Programming</a>
<span class="toggle" style="cursor:pointer"><i class="fa fa-plus" aria-hidden="true"></i></span>
<ul class="dropdown">
<li><a href="/programming/php/">PHP</a></li>
<li><a href="/programming/c/">C#</a></li>
</ul>
</li>
<li>
<a href="/frameworks/">Frameworks</a>
<span class="toggle" style="cursor:pointer"><i class="fa fa-plus" aria-hidden="true"></i></span>
<ul class="dropdown">
<li><a href="/frameworks/laravel/">Laravel</a></li>
</ul>
</li>
<li><a href="/data-analysis/">Data Analysis</a></li>
<li>
<a href="/cms/">CMS</a>
<span class="toggle" style="cursor:pointer"><i class="fa fa-plus" aria-hidden="true"></i></span>
<ul class="dropdown">
<li><a href="/cms/wordpress/">WordPress</a></li>
<li><a href="/cms/joomla/">Joomla</a></li>
</ul>
</li>
</ul>
No special CSS involved.