Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to play gif whenever button is clicked in javascript modal

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" class="modals">

  <!-- Modal content -->
  <div class="modal-contents">
    <img src="sample.gif" style="margin-top:-25%;margin-left:20%;width:60%">
    <span class="closes">&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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading