tomdes tomdes -4 years ago 93
jQuery Question

Removed class when click outside div but keep removed when div is closed

I have a div which open when I click on the question mark icon (upper right of the document).
When clicked I add a class which transform the question mark icon in close icon.
When I click outside the div, the div closed and the class is removed, closed icon becomes the question mark icon.
But now when I click in the document, it add and removed the class whenever the div is open or closed.

If anybody have an idea how I can removed the class when cliked on the document only when the div is open.
Thanks

jQuery('.showmenu').click(function(e){
e.stopPropagation();
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideToggle('fast');
});

jQuery('.about').click(function(e){
e.stopPropagation();
});

jQuery(document).click(function(){
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideUp('fast');
});

Answer Source

IMO add/bind $(document).click only when/on $('.showmenu').click function. Later do $(document).unbind('click') in $(document).click function

ex:

$('.showmenu').click(function (e) {
        e.stopPropagation();
        $('.about-btn').toggleClass("active");
        $('.about').slideToggle('fast');

        //Binding click function on document
        $(document).click(function () {
            $('.about-btn').toggleClass("active");
            $('.about').slideUp('fast');

            $(document).unbind('click'); //Unbind click
        });

    });

$('.about').click(function (e) {
    e.stopPropagation();
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download