简体   繁体   中英

Closing a modal by clicking outside of the modal

I have a modal window build with CSS. The modal can be closed by clicking outside of it.

My solution to open the modal works, closing the modal works too, when the event listeners are added to the page separately. However, they don't work together. When both the listeners are added to the page, the modal won't open.

How can I make them to work together?

HTML

<a href="#openModal" id="modal-window" class="event test">
  <div class="shorten-long-text test">
  </div>
</a>

<div id="openModal" class="modalDialog Dialog1">
  <div class="myModal">
    <div class="modal-header">
    </div>
    <div class="modal-body row">
      <div class="col-xs-6" >
      </div>
    </div>
    <div class="modal-footer uppercase color-main">
      <a href="#close" title="Close"></a>
    </div>
  </div>
</div>

JS

$(window).click(function(ev) {
    if($(ev.target).attr('class') != ".Dialog1" ) {
        $(".Dialog1").removeClass('isOpen');
        $(".Dialog1").addClass('isClosed');
    }
});

$(".test").click(function() {
    $(".Dialog1").removeClass('isClosed');
    $(".Dialog1").addClass('isOpen');
});

Use toggleClass() html:

<div id="openModal" class="modalDialog isClosed Dialog1">

js:

$(window).click(function(ev) {
if(!$(ev.target).is('.Dialog1,.test')  $(".Dialog1").toggleClass('isClosed isOpen');
}                                       
});

$(".test").click(function() {
$(".Dialog1").toggleClass('isClosed isOpen');
});

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