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() { = "block";


span.onclick = function() { = "none";

modal.onclick = function() { = "none";

window.onclick = function(event) {
  if ( == modal) { = "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>


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

>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() { = "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.

Leave a Reply Cancel reply