Reputation: 83
I'm trying to make a giphy clone and I want to display six of the trending gifs at the moment. However, when I run the code it seems to work fine in the sense of being able to grab the image source from the response data but the actual gif is not being displayed.
I tried using some of the different url and mp4 links provided in the response data but it always ends up displaying just the image tag.
function getTrending() {
// Create AJAX request to get the trending gifs
// Create the new XHR object
let xhr = new XMLHttpRequest();
// Call the open function with a GET-type request, url, and set async to true
xhr.open('GET', 'http://api.giphy.com/v1/gifs/trending?&api_key=<MyApiKey>&limit=6', true);
// Call the onload function
xhr.onload = function() {
// Check if the server status is 200
if(this.status === 200) {
// Return server response as an object using JSON.parse
let trendingResponse = JSON.parse(this.responseText);
// Create for in loop to insert the trending gifs into the gif container div
for (i in trendingResponse.data) {
gifsContainer.append("<img src='"+ trendingResponse.data[i].images.original.url+"' />")
}
console.log(trendingResponse.data[1]);
}
}
Upvotes: 2
Views: 208
Reputation: 66208
That is because when you use append()
, you are actually appending actual text instead of an element/node to your gifsContainer
:
The
ParentNode.append()
method inserts a set ofNode
objects orDOMString
objects after the last child of theParentNode
.DOMString
objects are inserted as equivalentText
nodes.
You should construct the image element by using new Image()
and then append it instead:
for (i in trendingResponse.data) {
const image = new Image();
image.src = trendingResponse.data[i].images.original.url;
gifsContainer.append(image);
}
If you're more comfortable using document.createElement()
, that's also possible:
for (i in trendingResponse.data) {
const image = document.createElement('img');
image.src = trendingResponse.data[i].images.original.url;
gifsContainer.append(image);
}
Upvotes: 2