skip to Main Content

Sorry I’m pretty hopeless with Javascript. I have a script that shows a popup which then fades out. But I cannot get it to reset. The code as it stands only works once.

function myFunction$users5() {
  var pop = document.getElementById("myPopup$users5");
  pop.classList.add("show");


  setTimeout(function() {
    $('#myPopup$users5').fadeOut('fast', function() {

      pop.classList.remove("show");
    });
  }, 3000);
}
<div class="popup" onclick="myFunction'.$users5.'()"><img src="unlovesm.png" style="float:right"><span class="popuptext" id="myPopup'.$users5.'">Login to Like.</span></div>

The popup shows and fades out correctly but thats it. Clicking the div again doesn’t show the popup a second time.

2

Answers


  1. I don’t use jQuery, but it looks like you tell it to fade out your div, but never have it fade it back in again. One way of dealing with that is to use jQuery’s fadeToggle() and match it up with the classList.toggle().

    function myFunction$users5() {
      var pop = document.getElementById("myPopup$users5");
      pop.classList.toggle("show");
    
    
      setTimeout(function() {
        $('#myPopup$users5').fadeToggle('fast', function() {
    
          pop.classList.toggle("show");
        });
      }, 3000);
    }
    <div class="popup" onclick="myFunction'.$users5.'()"><img src="unlovesm.png" style="float:right"><span class="popuptext" id="myPopup'.$users5.'">Login to Like.</span></div>
    Login or Signup to reply.
  2. To fix this, you can modify your myFunction$users5() to toggle the visibility of the popup by checking if the "show" class is already present. Here’s how you can do it:

    function myFunction$users5() {
      var pop = document.getElementById("myPopup$users5");
      
      if (!pop.classList.contains("show")) {
        // Popup is hidden, show it
        pop.classList.add("show");
      } else {
        // Popup is shown, fade it out and remove "show" class after fade out
        $('#myPopup$users5').fadeOut('fast', function() {
          pop.classList.remove("show");
        });
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search