2

I have menu with three levels:

HTML:

<ul class="main-menu">
    <li><a href="#">About</a></li>
    <li>
        <a href="#">Blog</a>
        <ul class="level2">
            <li>
                <a href="#">item1</a>
                <ul class="level3">
                    <li><a href="#">item 3</a></li>
                    <li><a href="#">item 4</a></li>
                </ul>
            </li>
            <li><a href="#">item2</a></li>
        </ul>
    </li>
    <li><a href="#">Contact</a></li>
</ul>

CSS:

.main-menu li a {
    color: #000;
}
.level3,
.level2 {
    display: none;
}
.main-menu li.active .level2 {
    display: block;
}

.level2 li.active .level3 {
    display: block;
}

Script:

$('.main-menu > li').click(function () {
    $(this).toggleClass('active');
});

$('.level2 > li').click(function () {
    $(this).toggleClass('active');
});

The problem is that when I click on an element of the second level, then the list of the third does not open. How to fix it? And how to refactor the code not to be repeated?

DEMO

1 Answer 1

4

Use event.stopPropagation() tp prevent bubling of events from child to parent elements.

DEMO

$('.main-menu > li').click(function () {
    $(this).toggleClass('active');
    $('.level2 > li').removeClass('active');
});

$('.level2 > li').click(function (event) {
    $(this).toggleClass('active');
    event.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

1 Comment

When I click on the items in the main menu, then all of them added class active! How fix?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.