Home > OS >  Need to add delay to the model popup ( Pure JS )
Need to add delay to the model popup ( Pure JS )

Time:08-11

How to add delay to the popup... I Tryed couple of silution but didnt work, What's the trick to achieve delay to the below model.

Thanks in advance

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");

function toggleModal() {
    modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
    if (event.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
.show-modal {
    opacity: 1;
    visibility: visible;
    transform: scale(1.0);
    transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<button >Click the modal!</button>
<div >
    <div >
        <span >×</span>
        <h1>Hello, I am a modal!</h1>
    </div>
</div>

Thanks

CodePudding user response:

delays are achive with timeout

function toggleModalDelayed() {
    setTimeout(()=>{
        modal.classList.toggle("show-modal");
    }, milliseconds)
}

CodePudding user response:

You can use the setTimeout method to add delay

It takes a method and a delay in millisecond as setTimeout(functionRef, delay).


Here is an exmaple for delaying the modal by 1s

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");

function toggleModal() {

  setTimeout(() => {
    modal.classList.toggle("show-modal");
  }, 1000)
    
}

function windowOnClick(event) {
    if (event.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
.modal {
  opacity: 0
}

.show-modal {
    opacity: 1!important;
    visibility: visible;
    transform: scale(1.0);
    transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<button >Click the modal!</button>
<div >
    <div >
        <span >×</span>
        <h1>Hello, I am a modal!</h1>
    </div>
</div>

CodePudding user response:

you can use css transition-delay property.

Here is the guide

  • Related