Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda