1

I making a single page website. When I open my menu and click on a li item, I want my menu to close.

For the moment it is working when I click back on the "menu-burger-wrapper" and I want to set the same thing when I click on items li.

There is my code:

$(document).ready(function() {

    $('#menu-burger-wrapper').click(function(e) {
        e.preventDefault();
        $this = $(this);
        if ($this.hasClass('is-opened')) {
            $this.addClass('is-closed').removeClass('is-opened');
        } else {
            $this.removeClass('is-closed').addClass('is-opened');
        }
    })
});
<nav class="menu-base" id="menu-base">
    <ul class="menu-item">
        <a id="en-cours" class="work_menu link link--over">
            <li>works</li>
        </a>
        <a class="about_menu link link--over">
            <li>about</li>
        </a>
        <a class="link link--over">
            <li>contact</li>
        </a>
    </ul>
</nav>
<!-- Header -->
<div id="header">
    <!-- Menu -->
    <div id="menu-burger-wrapper">
        <div id="menu-burger">
            <div class="line line-1"></div>
            <div class="line line-2"></div>
            <div class="line line-3"></div>
        </div>
    </div>

2 Answers 2

2

Try this - just attach the click handler to the li elements.

var clickHandler = function (e) {
    e.preventDefault();
    $this = $(this);
    if ($this.hasClass('is-opened')) {
        $this.addClass('is-closed').removeClass('is-opened');
    } else {
        $this.removeClass('is-closed').addClass('is-opened');
    }
};

//attaching the event to both, together.
$('#menu-burger-wrapper, ul.menu-item li').on('click', clickHandler);
1

You can use toggleClass to toggle class.

You can use , to separate the elements on which you want to bind event.

$('#menu-burger-wrapper, .menu-item').on('click', function (e) {
    e.preventDefault();
    $(this).toggleClass('is-opened is-closed');
});

$('.menu-item').on('click', 'li', function() {
    $('#menu-burger-wrapper').trigger('click');
});

Demo: https://jsfiddle.net/tusharj/7c5nd7rj/1/

1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.