Answer the question
In order to leave comments, you need to log in
Why doesn't the if else construct work?
Here is a link to an example dev.sholex.ru/acc.html
It is necessary that when clicking on the li element, the active class is assigned to it, but when clicking on another li, it is deleted
. In the example, there is an accordion, where the penultimate menu item (about the company) has a double nesting, so here's how to implement it so that when clicking on the Jobs menu item, its parent li (about the company) does not lose the active class, I
try with the if else construction to check the display block of the child ul element, but somehow it doesn’t work out
if ($('.sub-menu').css('display') !== 'block'){
$(this).addClass('active');
}
else{
$('li.menu-item-has-children').removeClass('active');
};
Answer the question
In order to leave comments, you need to log in
No need to look for logic, where it is most likely not.
They declared it for sure so that the IDE does not swear at an undeclared variable, since it does not see it in the include
I would suggest this option:
1. When clicking, remember the element that was clicked
2. Reset the `active` class for all menu items
3. Set the class `active` for the saved element
4. In the loop, set `active` for its parents, while do not go beyond the menu
$('.sub-menu').css('display') - this is how css is set for the block "$('.sub-menu').css('display': 'block)
you make it easier,
$('li').on('click', function () {
if($(this).hasClass('active')){
$(this).removeClass('active');
}else {
$(this).addClass('active');
$(this).siblings().removeClass('active');
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question