David David - 15 days ago 11
CSS Question

Prevent custom modal from hidding when background is clicked

I've created a custom modal (not bootstrap) and would like it to make it so If I click the surrounding background, it closes the modal. However, with the code I've put together, clicking anywhere on the modal also seems to close the modal. I figure it might be something to do with z-indexing, but everthing i've tried hasn't worked.

The HTML:

<div class="overlay" onclick="closeModal();">
<div class="overlay-wrap">
<div class="modal">
This is my modal
<a href="javascript:;" onclick="closeModal();">X</a>
</div>
</div>
</div>


The CSS:

.overlay {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
position: fixed;
left: 0px;
top: 0px;
display:table;
z-index:9999;
.overlay-wrap {
display:table-cell;
vertical-align:middle;
text-align:center;
}
.modal {
display:inline-block;
text-align:left;
min-width:300px;
max-width:90%;
margin: 15px;
background: #fff;
}
}


The Javascript:

function closeModal(ev) {
$(ev.currentTarget).closest('.overlay').hide();
}

Answer

Just add a click event to your .modal and use event.stopImmediatePropagation. Snippet below:

$(".overlay,.close").on('click',function(e){
  $(".overlay").hide();
});

$('.modal').on('click',function(e){
  e.stopImmediatePropagation();  
});
.overlay {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    position: fixed;
    left: 0px;
    top: 0px;
    display:table;
    z-index:9999;
  }
    .overlay-wrap {
        display:table-cell;
        vertical-align:middle;
        text-align:center;
    }
    .modal {
        display:inline-block;
        text-align:left;
        min-width:300px;
        max-width:90%;
        margin: 15px;
        background: #fff;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overlay">
   <div class="overlay-wrap">
      <div class="modal">
          This is my modal 
          <a class="close" href="javascript:;">X</a>
      </div>
   </div>
</div>