Skip to content Skip to sidebar Skip to footer

Close Modal On Click On Body

I just need to have a modal close on click off of it. I tried 2 approaches: Targeting a click event on body and check if the modal has a class and if it does show it check the eve

Solution 1:

To simplify things you could wrap your modal dialogue within a container that is full width and height of the viewport. This way you can show or hide the parent container if it is clicked instead of showing and hiding just the dialogue.

This also allows you to add an overlay with css later on to increase the visibility of the modal.

$(function(e) {

  var modal = $(".modal-wrapper")
  $("#filter-button").click(function(e) {
    modal.toggleClass("show");
  });
  $(window).click(function(e) {
    if (e.target == modal[0]) {
      modal.removeClass("show");
    }
  });
});
.modal-wrapper {
  display: none;
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
}

.modal {
  width: 300px;
  height: 300px;
  background-color: red;
}

.show {
  display: block;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="filter-button">SHOW/HIDE</button><divclass="modal-wrapper"><divclass="modal"></div></div>

Post a Comment for "Close Modal On Click On Body"