Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

jquery - Multiple modals on with same element name on same page

I'm trying to make it so when a user clicks outside of a modal, it closes it. So far, it only works on the first modal, and not the second.

Here is my code:

$(window).click(function(e){
    $('.reportModal').each(function(){
        var modal = $(this);
        if (e.target == modal) {
            $('.reportModal').fadeOut();
        }
    });
    //if (e.target == $('.reportModal')[0] || e.target == ) {
    //    $('.reportModal').fadeOut();
    //}
});

I want to make it so it is effective on all of them. Any help is appreciated. Thanks.

question from:https://stackoverflow.com/questions/65839851/multiple-modals-on-with-same-element-name-on-same-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

when a user clicks outside of a modal, it closes it.

So... This can also be explained this way:

???If the user click on an element which has no parent having the modal class...

Now you have the click to open the modal should be "delayed" a little with the :visible" condition.

Here is a quick made demo:

$("button.open").on("click", function() {
  let modal = $("." + $(this).data("target"))
  setTimeout(function() {
    modal.fadeIn();
  }, 200)
})


$(document).on("click", function(e) {

  if ($(".reportModal").is(":visible") && $(e.target).closest(".reportModal").length === 0) {
    $(".reportModal").fadeOut(); // Whichever the opened one is... Close them all!
  }
});
.reportModal {
  display: none;
  position: fixed;
  top: 30%;
  left: 45%;
  border: 1px solid grey;
  border-radius: 30px;
  padding: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="reportModal one">
  <div>My custom modal #1</div>
</div>
<button class="open" data-target="one">open modal #1</button>

<div class="reportModal two">
  <div>My custom modal #2</div>
</div>
<button class="open" data-target="two">open modal #2</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...