Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!