skip to Main Content

I’ve got the modal box appearing after 3 seconds as well as a black background set to 50% opacity. Right now the box and background just appears right at 3 seconds, I can’t quite figure out how to have the opacity go from 0% (0.0) to 50% (0.5) starting at 3 seconds.

CSS:

.modal {
  display: none;
  position: fixed;
  z-index: 999;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  justify-content: center;
  align-items: center;
}

JS:

const modal = document.getElementById("myModal");

const span = document.querySelector(".close");

setTimeout(function () {
  modal.style.display = "flex";
}, 3000);

span.onclick = () => {
  modal.style.display = "none";
};

2

Answers


  1. Try this CSS

         #myModal {
      display: none;
      position: fixed;
      z-index: 999;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      justify-content: center;
      align-items: center;
      opacity: 1;
      transition-property: opacity;
      transition-duration: 5s;
      transition-delay: 3s;
    }
    

    it will fade in opacity

    Here are the bugs with your code. Your css was a class and not an ID. So, JS could not find the ID to trigger.

    I changed that to the ID name as defined in your JS

    Login or Signup to reply.
  2. Using an animation to get around the item being display none

    document.querySelector("#btn").addEventListener("click", () => {
      document.querySelector('.modal').classList.toggle("show");
    });
    .modal {
      position: absolute;
      left: 100px;
      right: 100px;
      width: 100px;
      height: 100px;
      border: 1px solid #000000;
      opacity: 0;
      background-color: #CCC;
      display: none;
    }
    
    .modal.show {
      display: block;
      opacity: 1;
      animation-name: showModal;
      animation-iteration-count: 1;
      animation-timing-function: ease-in;
      animation-duration: 1s;
    }
    
    @keyframes showModal {
      0% {
        opacity: 0;
      }
      100% {
        opacity: 1;
      }
    }
    <div class="modal">
      XXXXXXX
    </div>
    
    <button id="btn">click</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search