Reputation: 122
I've got this code which basically.. On click of a div, it loads up the paragraph and inserts it into the twitch api url. The script should be working but what happens is after the fadeOut the div remains empty. The console returns the error that twitchData isn't defined, but it is. So it should work like this: Click on the div -> Understand which div was clicked -< fadeOut + empty() the div -> get the paragraph text -> replace it inside the twitchApi link etcetera.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
});
function setData() {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
});
Upvotes: 0
Views: 46
Reputation: 61842
This is a scope issue. You need to pass 'twitchData' into your setData function. Right now it is only defined within your click event.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
$.getJSON(twitchApi, function(json) {
setData(json.streams)
});
});
function setData(twitchData) {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
});
});
Upvotes: 1