Gofilord
Gofilord

Reputation: 6641

Close a modal when the body is clicked

I have made a simple pure modal with CSS and Javascript. Here's the code:
HTML:

<button data-role="toggle-modal" data-toggle="#demo">Trigger</button>

<div class="modal-wrapper" id="demo" style="display: none">
    <div class="modal">
        Modal content
    </div>
</div>

CSS:

.modal {
    margin: 10% auto;
    padding: 1em;
    overflow: hidden;

    width: 40%;
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, .5);

    background: white;

    text-align: center;
}

.modal-wrapper {
    z-index: 1000;
    position: fixed;
    overflow: hidden;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .4);
}

JS:

$('button[data-role="toggle-modal"]').click(function() {
    var target = ($(this).attr('data-toggle'));

    $(target).fadeIn(175);
});

$('.modal-wrapper').click(function() {
    $(this).fadeOut(175);
});

You can check it out on this fiddle.
The problem is, if I click inside the modal itself, it closes, and I want to interact with the modal. Do I need CSS masking here? Or is there another solution?

Upvotes: 2

Views: 3535

Answers (3)

Daniel
Daniel

Reputation: 233

You need to prevent the click event is triggered in the child element.

$('.modal-wrapper').click(function(e) {
    if(e.target == e.currentTarget) {
        $(this).fadeOut(175);
    }
});

Upvotes: 3

K K
K K

Reputation: 18099

Just check for e.target in your code and based on that, fade the dialog.

Example:

$('.modal-wrapper').click(function(e) {
    if($(e.target).is('.modal-wrapper'))  $(this).fadeOut(175);
});

Demo: http://jsfiddle.net/gprf6Lna/3/

Upvotes: 0

DaniP
DaniP

Reputation: 38252

Use StopPropagation, try this:

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

Check the Demo Fiddle

Upvotes: 1

Related Questions