首页 > 解决方案 > keep modal open despite clicking on it

问题描述

I'm trying to get a toggling modal to stay open even when it's clicked on. It has multiple elements inside of it as well, and if one of those is clicked it still needs to stay open. I asked a similar question about click events and event.target: close modal on click on body and this is a build off of that.

I figured out the previous question, which leaves me with this:

$(function(e) {

  $("#filter-button").click(function(e) {
    $(".dialog").toggleClass("show");
  });

  $(window).click(function(e) {
    if((e.target.tagName.toLowerCase() != 'button') && ($(".dialog").hasClass("show"))) {
    	$(".dialog").removeClass("show");
  	} else if (e.target.className.toLowerCase() == 'dialog') {
      return false;
    }
  });

});
.dialog {
  display: none;
  width: 300px;
  height: 300px;
  background-color: red;
}

.show {
  display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="filter-button">SHOW/HIDE</button>

<div class="dialog">
  <h1>Hi</h1>
  <ul>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
  </ul>
</div>

To explain what I'm trying to do - if the event target in the first if in the window click event is not the button and the dialog is showing, then remove it (expected functionality) - I now need to keep it open if it's clicked inside.

My attempt is this piece:

...
else if (e.target.className.toLowerCase() == 'dialog') {
      return false;
    }
...

What I thought was going to happen is that if the div is clicked, it will return: false; and stay open, preventing the dialog from closing. But it closes anyway. I also need to somehow target all the elements inside of it.

I'm not sure at this point how to move forward? Do I need to include all elements inside the dialog somehow?

标签: javascriptjqueryhtml

解决方案


You need to stop the event from bubbling up to the parent element (which will close the modal, as expected). You can do that with the following code:

$('.dialog').click(function(event) {
  event.stopPropagation();
});

推荐阅读