0

I am making a simple API call to load a random picture on screen when a button is clicked. I would like the image to refresh and show a new random image each time I click the button. Currently it just keeps adding new pictures below the current one. How can I get it to refresh with a new random picture onclick without stacking them? Thanks

loadImage = (url) => {
          fetch(url)
            .then(response => response.json())
            .then(newResponse => displayData(newResponse,'dataDiv'))
        }            

        function displayData(apiResponse, divid){
            let gridDiv = document.getElementById("gridDiv");
            const imageDiv    = document.createElement("img");
            imageDiv.id = "Pic";
            imageDiv.src = apiResponse[0]['url'];
            gridDiv.appendChild(imageDiv);
        }        
<div class="container py-3">
        <button type="button" class=" btn btn-success" id="Button" onclick="loadImage('https://apicall###')"
          Load Random Pictures!
        </button>
      </div>
      <div class="container"> 
            <div class="data-grid-container" id="gridDiv"></div>
      </div>      
General Grievance
  • 4,555
  • 31
  • 31
  • 45
JGeho
  • 1
  • 1

1 Answers1

0

Change your function to remove any children in gridDiv and then append:

function displayData(apiResponse, divid) {
  let gridDiv = document.getElementById("gridDiv");
  const imageDiv = document.createElement("img");
  imageDiv.id = "Pic";
  imageDiv.src = apiResponse[0]['url'];
  // added code
  while (gridDiv.firstChild) {
    gridDiv.removeChild(gridDiv.firstChild);
  }
  // end added code
  gridDiv.appendChild(imageDiv);
}
Rob Moll
  • 3,345
  • 2
  • 9
  • 15