Skip to content
Advertisement

How to open and close a modal after 3 seconds without Bootstrap or Jquery

I’m new to learning JavaScript and I’m trying to open then close a custom message after 3 seconds of appearing but my function doesn’t work. The message appears but does not disappear… can you help me find the solution because I can’t find it alone. Thanks very much !

const confirmationMessage = document.getElementById("message_validation");

// launch confirmationMessage form 
const launchConfirmationMessage = () => {
  confirmationMessage.style.display = "flex";
}

//close confirmationMessage form
const closeConfirmationMessage = () => {
  confirmationMessage.style.display = "none";
}

// TimeOut du confirmationMessage
const timeOutConfirmMess = () => {
  setTimeout(closeConfirmationMessage, 3000);
}


// open and close window after 3s
function confirm() {
  if (launchConfirmationMessage() = true && closeConfirmationMessage() === false) {
    timeOutConfirmMess();
  }
}
console.log(confirm());
.message-validation {
  display: none;
  align-items: center;
  justify-content: center;
  position: fixed;
  z-index: 1;
  left: 13%;
  top: 41%;
  overflow: auto;
  background-color: rgba(26, 39, 156, 0.9);
  color: white;
  padding: 5%;
  border-radius: 5px;
}
<div id="message_validation" class="message-validation">
  Bravo! Votre réservation est prise en compte.
</div>

Also, basically the css element is in display:none and it is during a condition that it becomes display:block like this:

if (isOk){ confirm();}

Thanks you again !

Advertisement

Answer

First your if statement is not correct. In a if statement you always compaire two things and you use “==” or “===”. You also doesn’t return any values in your helper function.

For this code I wouldn’t recommend a helper function, the code below will work.

const confirmationMessage = document.getElementById("message_validation");
// open and close window after 3s
function confirm () {
  confirmationMessage.style.display = "flex";
  setTimeout(() => {
      confirmationMessage.style.display = "none";
  }, 3000)

}
  console.log(confirm());
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement