简体   繁体   中英

Jquery - Prevent click event from being triggered through an overlying layer

.PopBgd is 100% of the screens size with another div .PopUp contained within .PopBgd and appearing on top of it. Clicking on .PopBgd gives the desired effect of Hiding. However clicking anywhere in PopUp also runs the fadeOut part of the script below.

QUESTION How to prevent the fadeOut part of the script from triggering though overlying divs?

$('.BtnPop').click(function(e) {
    e.preventDefault();
    $($(this).data('popup')).fadeIn();
    $('.PopClose, .PopBgd').click(function() {
    $('.PopBgd').fadeOut();});
});

ANSWER

<button type="button" class="BtnPop" data-popup=".Pop1">CLICK</button>

<div class="Pop1 PopBgd">
  <div class="PopUp">
    <a class="PopClose">&#215;</a>
    <div>Content</div>
  </div>
</div>

$('.BtnPop').click(function(e) {
    e.preventDefault();
    $($(this).data('popup')).fadeIn();
});
$('.PopClose, .PopBgd').click(function() {
$('.PopBgd').fadeOut();});

$('.PopUp').click(function(e) {
    e.stopPropagation();
});

NEW QUESTION How to use StopPropogation when the target div's name is unknown? What I have tried above does not work.

I resolved my additional problem by simply adding a second class name that was static to the desired div to allow stopPropogation to work as normal.

$('.Pop').click(function(e) {
    e.stopPropagation();
});

.stopPropagation() "Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM