Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
JavaScript/HTML - Replace GIF instead of adding by button click

I have already seen a couple of the same questions but I can't seem to get it right. I want to generate a new GIF with a button click. I got as far as generating a GIF by a button click. The problem is that when I click the button again it adds another GIF instead of replaced the previous one.

This is the code I have now:

HTML Button

        <form>
          <button
            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
            type="button"
            id="btnGIF" 
            style="display: inline; 
            transition: all 0.15s ease 0s; 
            text-align: center; 
            width: 50%;
            z-index:1;
            position: relative; 
            padding: 3%;">Generate GIF
          </button>
      </form>

And this is the JavaScript code I have:

document.addEventListener("DOMContentLoaded", init);
  function init() {
    document.getElementById("btnGIF").addEventListener("click", ev => {
        let APIKEY = "Dsuxat5V1ccrtvIIBdrxk731WPrSs22l";
        let RandomNumber = Math.floor(Math.random() * (100 - 1) + 1);
        ev.preventDefault(); 
        let url = `https://api.giphy.com/v1/gifs/search?api_key=${APIKEY}&limit=100&q=thankyou&offset=${RandomNumber}`;
        console.log(APIKEY)
        console.log(url);
        //var image_x = document.getElementsByClassName('out').classList.length;
        //console.log(image_x);
        //if (image_x > 0){
        //    PrevImage = document.getElementsByClassName('out')
        //    PrevImage[0].parentNode.removeChild(PrevImage[0]);
        //    }
        fetch(url)
        .then(response => response.json())
        .then(content => {
        console.log(content.data);
        console.log('META', content.meta);
        let fig = document.createElement("figure");
        let img = document.createElement("img");
        img.src = content.data[0].images.downsized.url;
        img.alt = content.data[0].title;
        fig.appendChild(img);
        let out = document.querySelector(".out");
        out.insertAdjacentElement("afterbegin", fig);
            })
        .catch(err => {
            console.error(err);
        })
    });
}

I do see that I'm appending the new gif instead of replacing it. I just can't find a way to replace it (I just started learning JavaScript).

Could someone help me?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have to remove the previous gif from the html element that it is being appended, which in this case is the element with class 'out'. An easy way to do this is to clear all the children from that class before appending the new element. The snippet below will be setting the HTML of the children of the 'out' class to blank.

document.querySelector(".out").innerHTML = ""

You can put this line right above where you set the api key, the first line within the click listener. Also, it is good practice not to post your api key on stack overflow. Best to leave that blank here.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda