I literally am lost with this project, I basically want to make a page that shows the status of twitch channels. Here is the codepen link.
Problem is the loop seems to finish before the else statement even completes, so it just shows 1 channel info everytime. Its just screwed up all around.
I just want to display some info for every twitch channel i have inside my channels array.
$(document).ready(function(){
function gatherChannels(){
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for(var i=0;i<channels.length;i++){
currentChannel = channels[i];
(function(someVar){ //<-- and u will get it here
currentChannel = channels[someVar]; // all ur code
})(i);//< -- here u pass ur loop i value
$.getJSON("https://api.twitch.tv/kraken/streams/" + channels[i] + "?callback=?", function(data){
if (data.stream !== null){
$(".main-area").append("<div class ='channels' id='currentChannel'>" + data.stream.channel.status + "</div>");
}
else{
$.getJSON("https://api.twitch.tv/kraken/channels/" + currentChannel + "?callback=?", function(info){
$(".main-area").append("<div class ='channels' id='currentChannel'>" + info.url + "</div>");
});
}
});
}
}
gatherChannels();
});
Your currentChannel variable is being set in a loop which is being modified by your loop, by the time your first ajax request has been returned the loop has already ended which is why your info.url is the last one.
you could put your ajax call into its own function as shown below.
$(document).ready(function() {
function gatherChannels() {
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"],
getChannel = function getChannel(channel) {
$.getJSON("https://api.twitch.tv/kraken/streams/" + channel + "?callback=?", function(data) {
if (data.stream !== null) {
$(".main-area").append("<div class ='channels' id='currentChannel" + channel + "'>" + data.stream.channel.status + "</div>");
} else {
$.getJSON("https://api.twitch.tv/kraken/channels/" + channel + "?callback=?", function(info) {
$(".main-area").append("<div class ='channels' id='currentChannel'" + channel + ">" + info.url + "</div>");
});
}
});
}
for (var i = 0; i < channels.length; i++) {
getChannel(channels[i]);
}
}
gatherChannels();
});
body {
background-color: black;
color: #fff;
}
h1 {
text-align: center;
background-color: gray;
padding: 20px;
}
.main-area {
margin-left: auto;
margin-right: auto;
}
.channels {
background: blue;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
color: white;
}
<html>
<head>
<title>Twitch Streamer Status</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="main-area">
<h1>Twitch Streamers</h1>
</div>
</div>
</body>
</html>