I'm writing a script that pulls data from a Twitch.tv API for a number of channels specified in an array, and then populates a table with the name of the channels and what's streaming. Here's the JS code followed by the HTML:
var channels = ["ESL_SC2", "freecodecamp", "OgamingSC2", "noobs2ninjas"];
$(document).ready(function() {
$( window ).on("load", function() {
for (var i = 0; i < channels.length; i++) {
$.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + channels[i] + "?callback=?", function(json) {
var json = JSON.stringify(json);
var obj = JSON.parse(json);
var streamStatus = obj.stream;
if (streamStatus === null) {
streamStatus = "Offline";
}
else {
streamStatus = "Streaming " + obj.stream.channel.status;
}
var para = document.createElement("div");
var node = document.createTextNode(streamStatus);
para.appendChild(node);
var element = document.getElementById("status");
element.appendChild(para);
});
}
for (var i = 0; i < channels.length; i++) {
var para = document.createElement("div");
var node = document.createTextNode(channels[i]);
para.appendChild(node);
var element = document.getElementById("title");
element.appendChild(para);
}
});
});
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6 center-column">
<h3>Twitch.tv Viewer</h3>
<div class="row">
<div class="col-sm-2" id="title"></div>
<a href="" id="link" target="_blank" style="text-decoration:none;"><div id="status"></div></a>
</div>
</div>
<div class="col-sm-3"></div>
</div>
Here's my problem: every time the page loads, the order of the items in the second column (the 'status' div, letting you know what's streaming) ends up in a different order, which means they no longer line up correctly with the channels in the first column (the 'title' div).
I suspect it has something to do with the API call, and the for loop being asynchronic, as suggested here. But I can't figure out how to implement the solution proposed. Any advice would be greatly appreciated!