Home > Net >  HTML pop up works only when clicked every 2nd time
HTML pop up works only when clicked every 2nd time

Time:03-26

I new to the html and css. I am now learning about the pop up and have come across an issue. Check out this simple fiddle: https://jsfiddle.net/74agLucr/

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}


/* The actual popup */

.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
}


/* Popup arrow */

.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}


/* Toggle this class - hide and show the popup */

.popup .show {
  opacity: 0;
  /* add this */
  visibility: visible;
  -webkit-animation: fadeIn 3s;
  animation: fadeIn 3s;
}

@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<h2>Popup</h2>
<div  onclick="myFunction()">Click me to toggle the popup!
  <span  id="myPopup">A Simple Popup!</span>
</div>

When you click on the text, the pop up shows up and disappears shortly. When clicked again, it will not do anything. I must click twice for it to pop up again. Could someone point me in the right direction and help me understand what is the issue?

CodePudding user response:

The problem with the popup is that toggle adds a class if it isn't added and removes if already was added. That's why you have to click twice in order for it to work. You can try setting setTimeout() so it toggles off after 3 second animation.

function myFunction() {
  var popup = document.getElementById("myPopup");
    if(!popup.classList.contains("show")){
  popup.classList.add("show");
  setTimeout(()=>{popup.classList.remove("show");}, 3000);
  }
}
  • Related