Home > OS >  how to play gif whenever button is clicked in javascript modal
how to play gif whenever button is clicked in javascript modal

Time:02-03

i have a modal in javascript, when user clicks the modal button, the modal opens with a gif:

var modal = document.getElementById("myModals");


var btn = document.getElementById("myBtns");


var span = document.getElementsByClassName("closes")[0];

btn.onclick = function() {
  modal.style.display = "block";

}


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

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


window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
<a href="#" id="myBtns"></a>

<div id="myModals" >

  <!-- Modal content -->
  <div >
    <img src="sample.gif" style="margin-top:-25%;margin-left:20%;width:60%">
    <span >&times;</span>
  </div>

</div>

so the issue here is the gif is played the first time, when user closes it and clicks button again the gif is displayed as it is without playing, can anyone please tell me what is wrong in here, thanks in advance

CodePudding user response:

To play the GIF each time the button is clicked, you need to reset the src attribute of the img element each time the button is clicked. Here's an example:

const playGifBtn = document.getElementById("playGif");
const gifImage = document.getElementById("gifImage");

playGifBtn.addEventListener("click", function() {
  gifImage.style.display = "block";
  gifImage.src = "";
  gifImage.src = "yourGif.gif";
});

This will reset the src attribute of the img element, effectively "restarting" the GIF each time the button is clicked. You can update your code accordingly.

  • Related