0

I am working on the Twitch Streamers app (freecodecamp project) where I have to show online and offline users. I think something is wrong with the way I wrote the loop for each username in the array because everytime I pressed the Online or Offline button, it keeps looping through and create another list of users. Can anyone tell me how to fix it? Thank you! Here is my JS code:

$(document).ready(function(){
  var client_id = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  var api = 'https://wind-bow.gomix.me/twitch-api/streams/'; 
  var newHTML=[];



  $.each(client_id,function(i,val){


    var stream_link = api + val + '?callback=?';

    $.getJSON(stream_link,function(data){
      $("#all_users").click(function(){
      newHTML.push('<span>' + val + '</span>');
      $("#display").html(newHTML.join("   "));


  })
      //$("#display").empty;
      if (data.stream == null){

        $("#offline").click(function(){

          newHTML.push('<span>' + val + '</span>');
          $("#display").html(newHTML.join("   "));})


      }

      else{
        $("#online").click(function(){

          newHTML.push('<span>' + val + '</span>');
          $("#display").html(newHTML.join("   ")); 

    })
      }
  })


  })


})

And here is the link of the rough draft of my project: https://codepen.io/cmtran/pen/QgXbWK

ChuChu
  • 339
  • 7
  • 19
  • You're never clearing newHTML. Each time the code runs it's appending the new content to the array and then replacing the HTML with what's in that array (which contains all previous content plus the new items). – JBC Aug 02 '17 at 15:18
  • Thank you for your feedback! How do I clear it? I tried .empty() but it did not work – ChuChu Aug 03 '17 at 03:12
  • In your case I'd just do `newHtml = [];` See this answer: https://stackoverflow.com/a/1232046/2193107 – JBC Aug 03 '17 at 15:10

0 Answers0