i am working twitch tv api.api calls should me made equal to number of elemnts in streamer array.but it is call multiple times.u can see it on codepen.
jsfiddle linkhttps://jsfiddle.net/o48wwLdf/ html
javascript code
$(document).ready(function() {
var i;
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; //streamers array
for (i = 0; i < streamers.length; i++) {
jsoncall(streamers[i]); //calling function for api calls.
}
});
function jsoncall(stream) { //function for api call
$.getJSON('https://api.twitch.tv/kraken/streams/' + stream + '?callback=?', function(data) {
if (data.stream === null) { //if channel is offline display offline
$("p").append("<p>" + stream + " offline</p>");
} else { //if channel is online show what is he streaming.
$("p").append("<p>" + stream + data.stream.game + "</p>");
}
});
}
When you do this:
$("p").append(...);
the content is appended to every <p>
element on the page. Since you're adding more <p>
elements in the content, you get duplicates all over the place.
Here's a forked version of your CodePen. I added an id to the main <p>
element. Note that appending a <p>
to a <p>
doesn't really make sense anyway; <p>
elements can't contain block-level elements like other <p>
elements. Browsers allow it however. So, the HTML:
<p id=main></p>
And the updated JavaScript:
function jsoncall(stream) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + stream + '?callback=?', function(data) {
if (data.stream === null) {
$("#main").append("<p>" + stream + " offline</p>");
} else {
$("#main").append("<p>" + stream + data.stream.game + "</p>");
}
});
}