In my React project, I'm attempting to develop a function that generates a new element displaying a gif for one loop before removing it. My current approach looks like this:
function playGif() {
var gif = document.createElement('img')
gif.className = "gif-play"
document.body.appendChild(gif)
setTimeout(() => { gif.parentNode.removeChild(gif); }, 600)
}
This is complemented by the following CSS styling:
.gif-play {
width: 256px;
height: 256px;
position: absolute;
background-image: url(./assets/images/animations/atk1.gif);
background-size: cover;
}
Despite adjusting the timeout duration to match the gif's precise length, the gif starts to clip and play from the middle after multiple button clicks.
I've also experimented with setting the image src directly utilizing the require() function:
function playGif() {
var gif = document.createElement('img')
gif.src = require('./assets/images/animations/atk1.gif')
document.body.appendChild(gif)
setTimeout(() => { gif.parentNode.removeChild(gif); }, 600)
}
However, this method resulted in only showing a broken image instead of the gif itself. Even though I expected require() to solve the issue, it still doesn't seem to work as intended in my case.
If you have any insights on how to ensure the gif plays from the beginning when calling the function, I would greatly appreciate your advice. Thank you!