0
(function goGetThem() {
  var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  var base = 'https://wind-bow.gomix.me/twitch-api/';
  var jsonp ='?callback=?';

  function makeUrl(type, user) { //type is either channels or streams
    return base + type + '/' + user + jsonp;
  }
  users.forEach(function (user) {
    let status;
    $.getJSON(makeUrl('streams', user), function (data) {
      if (Boolean(data.stream === null)) {
        status = 'offline';
      } else {
        status = 'online';
      }
    });
    $.getJSON(makeUrl('channels', user), function (data) {
      if (status === 'online') {
        console.log('online', user); // !!here I have 2 online users
        addData('#online');
        $('#icon').wrap(`<a href="${data.url}"></a>`).addClass('online');
        // !! this line only applied to first user and not the second
        // !! there there are 2 users with status = 'online'
      } else {
        addData('#offline');
      }
      addData('#all');

      // function declaration
      function addData (selector) {
        let info = (status === 'online')? data.display_name + ' <br> ' + data.status : data.display_name;
        $(selector).append(`<div class="item" id="item">
        <img class='logoImage rounded-circle' src=${data.logo}>
        <div><p class="detail">${info}</p>
        <i id="icon" class="fa fa-circle"></i></div>`);
      }
    });
  });
})();    

I need a help with understand why a line of jquery is not being applied under the if/else statement. I am trying to add class online to change the color of icon(fa fa-circle).

As I left comments in code, I have 2 users with status value online, but this line below $('#icon').wrap().addClass('online');, is only applied to the first user but not the second user.

Any help would be much appreciated. Thank you.

  • 4
    *id selector* is meant only for one element. you're using `#icon` to refer to the element and you expect two elements to be modified? – Wreigh Feb 01 '18 at 03:49
  • 1
    aren't your two getJSON running async? so you may be setting status after you check it. the second getJSON should probably be a callback or a promise or async / await. something like that – Bryan Dellinger Feb 01 '18 at 03:54
  • simplest fix: move the code block `$.getJSON(makeUrl('channels', user), function (data) { ... });` above the preceding `});` – Jaromanda X Feb 01 '18 at 04:11
  • @Wreigh Thank you for your comment. I indeed am generating multiple elements with same ids. I thought it would be filtered already by if/else statement. – heathercoraje Feb 02 '18 at 05:09
  • @JaromandaX Yeah it was not done and therefore it was only applying to a few users only. Thanks! – heathercoraje Feb 02 '18 at 05:11

0 Answers0