Home > other >  Clicking anywhere in a modal triggers a close instead of outside only
Clicking anywhere in a modal triggers a close instead of outside only

Time:11-11

I have a fullscreen container with a dark background and then a modal div with text and a button. I want visitors to be able to click outside of the modal (or click the "x") to exit. Everything works fine except the modal disappears when I click inside the modal, which it shouldn't do.

I've seen multiple cases very similar to this (links below), so I originally thought this was a targeting problem, then a bubbling problem. I can't seem to make this work even when mimicking other setups as best I can. I'm okay with using vanilla JS or jQuery. Can anyone see what I'm missing?

HTML:

   <div id="fullscreen-background">
     <div id="my-modal">
        <span id="close-modal">X</span>
        <p>Some text</p>
        <a href="example.com" target="_blank">Link</a>
    </div>
 </div>

JS:

jQuery("#fullscreen-background").click(function(e){
    if(e.target == this){
        jQuery("#fullscreen-background").fadeOut("fast");
    }
});

Close modal windows on click anywhere outside of modals jQuery: click function exclude children.

CodePudding user response:

This happens because the click event bubbles up from the nearest selector to the parent-most selector.

You can prevent this behavior using event.stopPropagation();

jQuery("#fullscreen-background").click(function(e){
    event.stopPropagation();
    if(e.target == this){
        jQuery("#fullscreen-background").fadeOut("fast");
    }
});
  • Related