Kin
Kin

Reputation: 4596

How to close modal on next click after open?

I have the link with class control on which rises div with class popup. The problem is on how to close this div on the next click if this click is outside the div? At the moment this two events fires at the same moment and as a result modal don't appear. How to close this modal only on the next click.

jQuery(document).ready(function(){
    jQuery('body').on('click', function(event){
        var menu_popup = jQuery('div.popup[data-open-status="true"]');

        if(menu_popup.has(event.target).length === 0)
            menu_popup.hide().attr('data-open-status', 'false');
    });

    jQuery('a.control').click(function(event){
        event.preventDefault();
        jQuery('div.popup').show().attr('data-open-status', 'true');
    });
});

Upvotes: 0

Views: 182

Answers (1)

Bram Vanroy
Bram Vanroy

Reputation: 28485

You need to make sure that the click event doesn't bubble up the dom. Fiddle

jQuery(document).ready(function () {
    jQuery("a.control").click(function (e) {
        jQuery("div.popup").show().attr('data-open-status', 'true');
        e.preventDefault();
        e.stopImmediatePropagation();
    });

    jQuery(document).click(function (e) {
        var menu_popup = jQuery('div.popup[data-open-status="true"]');
        if (menu_popup.has(e.target).length === 0) menu_popup.hide().attr('data-open-status', 'false');
    });

    // Add a stopPropagation so that when a user clicks in the div, the event doesn't bubble up to "document"
    jQuery("div.popup").click(function (e) {
        e.stopPropagation();
    });
});

But it appears to me that you can leave out the data-attribute: http://jsfiddle.net/25xFu/1/

$("a.control").click(function (e) {
    $("div.popup").slideToggle("fast");

    e.preventDefault();
    e.stopImmediatePropagation();
});

$(document).click(function (e) {
    if ($("div.popup").is(":visible") && !$("div.popup").is(e.target)) {
        $("div.popup").slideUp("fast");
    }
});

$("div.popup").click(function (e) {
    e.stopPropagation();
});

Upvotes: 1

Related Questions