Nytrix Nytrix - 26 days ago 15
jQuery Question

JQuery - Click on background

I have a design with a layover, like this:

.layover{
width: 100%;
height: 100%;
display: none;
position: absolute;
background: rgba(0,0,1,0.7);
z-index: 1000;
}


I use show this when a button is clicked, easy. It has another div in it, but I want to close this things when the
.layover
is clicked. But if I click the form over it, it still closes!

My javascript trying to close it:

$(".layover").on("click", function(){
if(overlay_active){
$(".layover").fadeOut();
overlay_active = false;
}
});


How can I make it that just if I click
.layover
that it closes, and not if I click on the
childs
of
.layover
?

Answer

Try this:

$(".layover").on("click", function(e){
    if(e.target !== e.currentTarget) return;

    if(overlay_active){
        $(".layover").fadeOut();
        overlay_active = false;
    }
});
Comments