Weather App -- For loop with Skycons

Hi All,

My last element of this weather app is to show a 5 day forecast. Everything was working great, until I decided to use Skycons instead of the written summary. I’m obviously doing something wrong with my For loop because the first icon shows up, and the other 4 days are sadly icon-less. Can you see what I’m doing wrong?

// get weekly forecast
        var result = response.daily.data;
        
        for(var i = 0; i < 5; i++) {
          var iconForecast = icon[i];
          $forecast.append(
            "<div class='box'><canvas id='iconForecast' width='28' height='28'></canvas><br>" + Math.round(result[i].temperatureMin) 
            + "<br>" + Math.round(result[i].temperatureMax) 
            + "</div>"
          );
          skycons.add("iconForecast", result[i].icon);
          skycons.play();
        }

And the whole project: https://codepen.io/emorgan05/pen/NgEYNx?editors=0010

1 Like

Each canvas created for the icon needs to have a unique ID. Perhaps consider creating a unique ID using the for loop’s iterator i

for(var i = 0; i < 5; i++) {
  var uniqueId = 'iconForecast' + i;
  
  // when appending the canvas
 "<canvas id=" + uniqueId + "...></canvas>"

  // later
  skycons.add(uniqueId, result[i].icon);
}
2 Likes

Thanks! That worked.

I’m having trouble with the same method - for whatever reason, the variable I put in isn’t being evaluated by skycons.add( … ) correctly.

My code:

newElementHtml += "<div class='col-sm-3'>" + "<canvas id='icon_" + index + "' width='128' height='128'></canvas>" + "</div>";

var canvasName = "icon_" + index.toString();

skycons.add(canvasName, data.icon);

When I replace “canvasName” with a static string, e.g. “icon_0”, it displays correctly. I also tried printing “canvasName” and its type to double check it’s being set like I expected, and it’s giving the correct id and showing it as a string. Any idea what could be happening?

NEVER MIND. Mystery solved.

I didn’t append the whole HTML blob until after I called skycons.add, so the canvas wasn’t actually on the page yet.