0

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?

user2133561
  • 155
  • 1
  • 10
  • Yes, [`appendChild`](//developer.mozilla.org/docs/Web/API/Node/appendChild) obviously appends. Do you see a [different method](//developer.mozilla.org/docs/Web/API/Node#methods) in the DOM API that obviously replaces? – Sebastian Simon Feb 25 '22 at 14:37

1 Answers1

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.