Raj Raj - 1 month ago 16
Javascript Question

Unable to repeat click event

This is basically a menu toggle feature which I want to repeat but doesn't unless I refresh the page. Clicking on (.fa-bars) adds class (.animate) to body which slides in the menu from the left, when the menu is visible clicking anywhere outside the menu area hides the menu as well as removes the class(.animate) from body.

This only works once then I have to refresh the page to make it work again, please suggest a way to fix this.

jQuery code:

$(document).ready(function() {
$(document).on('click', function() {
if($('body').hasClass('animate')) {
$('body.animate').on('click', function() {
$(this).removeClass('animate');
});
} else {
$('.fa-bars').on('click', function() {
$('body').addClass('animate');
});
}
});
});

Answer

I think he want to close menu when click on body only. This code may help:

$(document).ready(function () {
    $('.fa-bars').on('click', function (evt) {
        $('body').addClass('animate');
        evt.stopPropagation();
    });

    $('body').on('click', function () {
        if ($('body').hasClass('animate')) {
            $('body').removeClass('animate');
        }
    });
});

Click on fb-bars to open menu

Click on body to close menu if already opened