Novice
Novice

Reputation: 535

target element in click event in nested divs

I have two nested divs

<div class="modal-container">
    <div class="modal-content"></div>
</div>

I am trying to implement a modal dialog effect. My CSS and jQuery works fine in showing the modal dialog.

When I try to hide the modal dialog with the following jQuery.

$(".modal-container").click(function (event) {
    $(this).hide();
});

It hides the modal-container but the problem is it hides it even when I click on modal-content div. What I want to achieve is the regular modal effect that allows to click inside content without dismissing the modal dialog but when clicked on the grayed area (outside the inner content div) it should dismiss the dialog.

How can we achieve it without using the id's of the divs as I have multiple content divs, and I want to work it with the class selectors.

Upvotes: 0

Views: 1727

Answers (3)

Alexandru Severin
Alexandru Severin

Reputation: 6238

You can use event.target to check if the clicked element is the .modal-container

$(".modal-container").click(function (event) {
    if(event.target == this){
        $(this).hide();
    }
});

But since you're already using jQuery, I recommend using a modal plugin, since they have this functionality and many others built-in (there are tons you can find for free)

Upvotes: 2

Akshay
Akshay

Reputation: 805

try this

$(".modal-container").click(function (event) {
    $(event.target).hide()

});

Upvotes: 0

Anupam
Anupam

Reputation: 8016

Your click event is bubbling up to the container which hides the modal. Read about it here.

On content click prevent click event to propagate

$(".modal-content").click(function (event) {
    event.stopPropagation();
});

More info on stopPrapagation

Upvotes: 0

Related Questions