Skip to content
Advertisement

Why isn’t my black overlay appearing when button is clicked?

I am trying to create a pop-up window myself. I want my pop-up box to appear when the button is pressed and everything below to get darkened. However, when I press my button whole page hangs and no popup appears also.

If I remove the div which turns everything background black, my popup is working fine.

Here is my html code which has script tags inside

let visible = false;
$('#showBox').on('click', function(params) {
  if (visible) {
    $('.box').removeClass('boxVisible');
    $('.blackenBackground').removeClass('boxVisible');
    visible = false;
  } else {
    $('.box').addClass('boxVisible');
    $('.blackenBackground').addClass('boxVisible');
    visible = true;
  }
})
.box {
  background: pink;
  height: 500px;
  width: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 3;
  transform: translate(-50%, -50%);
  border-radius: 1%;
  opacity: 0;
  transition: 0.4s;
  transition-timing-function: ease-out;
}

.boxVisible {
  opacity: 1;
}

.blackenBackground {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  background: black;
  opacity: 0;
  z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<p>Some lorem text.....
</p>

<button id="showBox">Show Box</button> 

<!-- When I remove this popup box works perfectly but background isn't darkening and my page hangs -->
<div class="blackenBackground"></div>

Advertisement

Answer

Your fixed position div is blocking mouse events. The opacity is 0 but the box is still technically visible, which catches the click and prevents the button from getting clicked.

Just make sure the box is completely hidden and it should work.

let visible = false;
$('#showBox').on('click', function (params) {
    if(visible){
        $('.box').removeClass('boxVisible');
        $('.blackenBackground').removeClass('boxVisible');
        visible = false;
    }else{
        $('.box').addClass('boxVisible');
        $('.blackenBackground').addClass('boxVisible');
        visible = true;
    }
})
.box{
    background: pink;
    height: 500px;
    width: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 3;
    transform: translate(-50%, -50%);
    border-radius: 1%;
    opacity: 0;
    transition: 0.4s;
    transition-timing-function: ease-out;
}

.boxVisible{
    opacity: 1;
    display: block;
}

.blackenBackground{
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100vw;
    background: black;
    opacity: 0;
    display: none;
    z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<p>Some lorem text.....</p>
<button id="showBox">Show Box</button>
<div class="blackenBackground"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement