Using the createElement method in React to restart a GIF animation

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!

Answer №1

Uncertain about your exact requirements, but here is an animation I have created for you to review. Hopefully, it will be beneficial for you.

PlayGifExample Component

import React, {useEffect} from "react";
import PlayGif from './PlayGif.css'

function PlayGifExample() {

    function animate(i) {
        if(i > 1000)
            return;
        let gif = document.createElement('img');
        gif.className = "gif-play";
        gif.style.cssText = `left: ${i}px`;
        console.log(i);
        document.body.appendChild(gif);
        setTimeout(() => {
            gif.parentNode.removeChild(gif);
            animate(i+1);
        }, 10)
    }

    function playGif() {
            let gif = document.createElement('img');
            gif.className = "gif-play";
            gif.style.cssText = `left: 1px`;
            document.body.appendChild(gif);
            setTimeout(() => {
                gif.parentNode.removeChild(gif);
                animate(2);
            }, 10)
    }

    return (
        <>
            <button onClick={playGif}>Click me</button>
        </>
    );
}

export default PlayGifExample;

PlayGif.css

.gif-play {
    width: 256px;
    height: 256px;
    position: absolute;
    background-image: url(./images/4.png);
    background-size: cover;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The 'Store' property is not found in the '{}' type but is needed in the 'Readonly<Istore>' type. TS2741

Can you assist me in resolving this issue? I am attempting to pass my store as props to the component, but I keep encountering the following error: Type error: Property 'Store' is missing in type '{}' but required in type 'Readon ...

Setting the default <a-sky> in Aframe: A step-by-step guide

There was a fascinating projection I witnessed where two images were displayed in the sky. [https://codepen.io/captDaylight/full/PNaVmR/][code] Upon opening it, you are greeted with two spheres and a default white background. As you move your cursor over ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...

Only one instance of a div with a table cell will function properly

I am facing an issue where I created a div with display:table-cell; and it appears as shown in the first picture, which is what I want. However, when I add another div, it changes to look like the second picture. All I want is for the text to be in the mid ...

Traverse through nested objects

I am currently working with JSON data containing information like uf, ivp, and others. My goal is to iterate over all the objects in order to access their properties. { "version": "1.5.0", "autor": "mindicador.cl", "fecha": "2018-10-31T13:00:00.000Z", "uf ...

Alter the responseType within Angular (5) once the response has been received

Is it possible to dynamically change the response type in the post method (angular 5) after receiving the response? The challenge: I need the response type to be blob when the response is successful, and json when there's an error. I've searc ...

Leveraging Material UI and Tailwind CSS in React-based developments

Can tailwind CSS and Material UI be used together in a React project without any class conflicts? ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

Encountered the error message "A property 'split' cannot be read of undefined" while attempting to run a React Native application

I was able to run a react-native app without any issues yesterday, but today when I tried to run it again, I encountered some problems. After running "npm start" to start metro, I then attempted to run "npx react-native run-android". However, I received th ...

Despite the use of v-if and v-else directives in Vue 2, a specific component properties are not being updated while the others are updating

Vue2 is not updating one specific component (<Button>) inside v-if and v-else, while the rest of the content is updated. I have recently discovered a solution to make this code function, but I am still unsure about Vue2 re-rendering behavior. I worr ...

Looking to extract a specific field using Angular JS?

The JSON data I need is fetched from the link provided below: http://maps.googleapis.com/maps/api/geocode/json?address=SFO When retrieving the JSON, only the parameter example ?adress=sfo should be used. This will result in fetching all values associated ...

What is the best approach to setting up dynamic Vue routing?

I am working on implementing dynamic routing for the website that relies on changes in agreements. Here is the path tree I have set up: const routes = [ { path: "/", redirect: "/home", component: DefaultLayou ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

'value' is connected to every single hook

Every time I try to save my work using any hook, the 'value' field changes automatically. This has been causing me a great deal of stress. I would be extremely grateful if someone could assist me with this issue. click here for image description ...

Implementing single sign-on across different domains with an express server, react client, and redirect functionality

To tackle the challenge at hand, I am working on developing a web application that involves a form submission to my express server. The process includes generating a token from an external endpoint post using the form value, utilizing this token from an ex ...

Material UI TableCell lacks the ability to wrap a string and display it on a new line, unlike list items

I am currently working with a "Books" database in Material UI. The table consists of three columns: "Book Number", "Title", and "Chapters". My goal is to have each chapter displayed as individual list items, like so: Chapter 1 Chapter 2 Chapter 3 Inste ...

Establish the geolocation within the data object once Vue.js has been mounted

Just dipping my toes into the world of VueJS. I've got a side project in the works that hinges on fetching User's Geolocation Data right after the main component has mounted. My code snippet is as follows: var app = new Vue({ el: '#app&a ...

Fetching the "User ID" variable from localStorage to PHP with angularjs - a quick guide

My goal is to retrieve "Notes" based on the "userID" value. Here is my approach: I used angular.js to trigger the PHP function $scope.getData = function(){ $http.get( '../php/displayNotes.php' ).success(function(data){ $ ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...