javascriptcssanimationmodal-dialogfadein

Get modal fade in in with display block CSS Javascript


I am struggling to get a modal get animated when a button is clicked. The modal must not take space when its hidden. So I want to use display none when its not shown. And when the button is clicked the modal needs to fade in. Now I have found a solution I think to make it work. But still it's not working. Could anyone tell me why its not working? An how I could get it to work?

<!DOCTYPE html>
<html lang="en">
    
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
    
<body>
  <h2>Animating from <code>display:none</code> to <code>display:block</code></h2>
  <div id="box" class="box"></div>
    
  <button>TOGGLE VISIBILITY</button>
</body>

<script src="script.js"></script>

</html>
.box {
  background: goldenrod;
  width: 300px;
  height: 300px;
  margin: 30px auto;
  transition: all 2s linear;
  display: none;
}
        
.show {
  display: block;
}
          
.visuallyshow {
  opacity: 0;
}
        
button {
  display: block;
  margin: 0 auto;
}
let box = document.getElementById('box'),
  btn = document.querySelector('button');
    
btn.addEventListener('click', function () {
  if (box.classList.contains('show')) {
    box.classList.remove('show');
    setTimeout(function () {
      box.classList.remove('visuallyshow');
    }, 20);
  } else {
    box.classList.add('visuallyshow');
    box.addEventListener('transitionend', function (e) {
      box.classList.add('show');
    }
    // , {
    //   capture: false,
    //   once: true,
    //   passive: false
    // }
    );
  }
}, false);

Solution

  • Here's what you need to do:

    let box = document.getElementById('box'),
        btn = document.querySelector('button');
    
    btn.addEventListener('click', function () {
    
        if (box.classList.contains('show')) {
            box.classList.remove('visuallyshow');
            setTimeout(function () {
                box.classList.remove('show');
            }, 2000);
        } else {
            box.classList.add('show');
            setTimeout(() => {
                box.classList.add('visuallyshow');
            }, 1);
        }
    
    }, false);
    .box {
      background: goldenrod;
      width: 300px;
      height: 300px;
      margin: 30px auto;
      transition: opacity 2s linear;
      display: none;
      opacity: 0;
    }
    
    .show {
      display: block;
    }
    
    .visuallyshow {
      opacity: 1;
    }
    
    
    button {
      display: block;
      margin: 0 auto;
    }
    <h2>Animating from <code>display:none</code> to <code>display:block</code></h2>
    <div id="box" class="box"></div>
    
    <button>TOGGLE VISIBILITY</button>