Greetings everyone, Thank you for taking the time to read through this post.
I am currently facing an issue while attempting to create a menu with sub-menus.
Here are the requirements for the menu:
- Sub-menus should open on click. (working)
Selected sub-menus should remain open. (working)
3. When clicking on other menus, previously opened sub-menus should close. (not working)
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bottom-menu">
<li class="drop"><a>Hyperlink 1</a></li>
<li class="drop"><a>Hyperlink 2</a>
<ul id="m1" class="bottom-menu-sub">
<li><a href="#">Hyperlink Sub</a></li>
<li><a href="#">Hyperlink Sub</a></li>
<li><a href="#">Hyperlink Sub</a></li>
</ul>
</li>
<li class="drop"><a>Hyperlink 3</a>
<ul id="m2">
<li><a href="#">Hyperlink Sub</a></li>
<li><a href="#">Hyperlink Sub</a></li>
</ul>
</li>
<li class="drop"><a>Hyperlink 4</a>
<ul id="m3">
<li><a href="#">Hyperlink Sub</a></li>
<li><a href="#">Hyperlink Sub</a></li>
</ul>
</li>
</ul>
CSS:
.bottom-menu li ul {
display:none;
}
JS:
jQuery(function ($) {
// jQuery code in here can safely use $
$('.bottom-menu li')
.css({
cursor: "pointer"
});
$(".drop>a").on('click', function (eventData) {
var $listItem = $(this).closest('li');
$listItem.find('ul').toggle();
$listItem.toggleClass('open');
$.cookie('open_items', 'the_value');
openItems = new Array();
$("li.drop").each(function (index, item) {
if ($(item).hasClass('open')) {
openItems.push(index);
}
});
$.cookie('open_items', openItems.join(','));
});
if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
previouslyOpenItems = $.cookie('open_items');
openItemIndexes = previouslyOpenItems.split(',');
$(openItemIndexes).each(function (index, item) {
$("li.drop").eq(item).addClass('open').find('ul').toggle();
});
}
});