I have menu list in my page with following structure. When I click any link in the menu the system automatically add class="is-active" to the link. I set display of nested links to none so they will be visible only by clicking on parent link (see css). However, when I click on one of the child links, the whole submenu of child links disappear. How to achieve that my child links will be visible when I use them? I know I cannot affect parent by child with css, maybe there is some simple javascript workaround.
Thank you in advance!
.menu-item--expanded ul {display: none;} .menu-item--expanded a.is-active ~ ul {display: block}
<html> <body> <ul> <li class="menu-item--expanded"> <a class="is-active">Link 1</a> <ul> <li><a href="">Link A</a></li> <li><a href="">Link B</a></li> <li><a href="">Link C</a></li> </ul> </li> <li class="menu-item--expanded"> <a>Link 2</a> <ul> <li><a href="" class="is-active">Link D</a></li> <li><a href="">Link E</a></li> <li><a href="">Link F</a></li> </ul> </li> </ul> </body> </html>
I would do something like this on javascript:
$('li').on('click', function(evt){
$(evt.target).parent().css('display', 'none');
})
so when a list item is clicked then set as display:none the parent element, so ul. Maybe have a check around the setting of css to check is-active class too, like:
if($(evt.target).hasClass('is-active')){
//switch to display none
}
i would suggest using jquery for this. The following code will change the display from the child ul when clicked on a parent.
make sure that the child lists are display: none with css.
.menu-item--expanded > ul{
display: none;
}
$('.menu-item--expanded').click(function () {
$(this).find($('ul')).css({
'display' : 'block'
});
});
to make sure that only the childs of the parent page where you are are visible use the following code:
note: the else clause is not needed actually since your css will already set display none on those items. but i mentioned it just to make it clear.
$('.menu-item--expanded').each(function () {
if($(this).find($('>a')).hasClass('is-active')){
$(this).find($('ul')).css({
'display' : 'block'
});
} else {
$(this).find($('ul')).css({
'display' : 'none'
});
}
});
hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.