I’m working on a project that fetches GIFs from the Giphy API. Right now my code only shows one image at a time, but I want to display multiple GIFs from the search results. The main issue is that I can see all the image URLs in the console, but I can’t figure out how to create separate elements for each one.
function executeSearch(searchTerm){
apiRequest.open('GET', 'https://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q='+searchTerm, true);
apiRequest.send();
};
$(document).ready(function() {
$('#submitBtn').click(function(event) {
var userInput = $('#searchInput').val();
apiRequest = new XMLHttpRequest;
apiRequest.open('GET', 'https://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q='+userInput, true);
event.preventDefault();
var buttonHtml = '<button class="historyBtn" data-search="'+userInput+'">'+userInput+'</button>';
$('#buttonContainer').append(buttonHtml);
apiRequest.onload = function() {
for (var j = 0; j < 10; j++) {
var gifUrl = JSON.parse(apiRequest.responseText).data[j].images.fixed_height.url;
console.log(gifUrl);
document.getElementById("resultsDiv").innerHTML += '<div><img src="'+gifUrl+'" alt="Giphy GIF"></div>';
}
};
apiRequest.onerror = function() {
console.log('API request failed');
};
apiRequest.send();
});
});
<div class="main-wrapper">
<div class="content">
<div id="buttonContainer"></div>
<form>
<div class="search-area">
<input id="searchInput" type="text" placeholder="Enter search term"/>
<button id="submitBtn" type="button">Find GIFs</button>
</div>
</form>
<div id="resultsDiv"></div>
</div>
</div>
The problem is that only the last GIF from the loop gets displayed. How can I modify this to show all the GIFs instead of just overwriting the same element?