Reputation: 100
I am trying to create a daily weather app and i'm having issues trying to figure out how to output the data into cards for all seven days. its currently only outputting the last day. I know that its because if am setting it to $("#card__days").html(
but im not sure how to add onto the current html.
Is there also any easier way to output this information? I feel like I did way too much for a simple task. Thank you
function updateDaily(data) {
Object.keys(data.daily.data).forEach(function (i) {
// call to find what the day is.
let date = calculateDay(data.daily.data[i].time);
console.log(data.daily.data[i]);
let iteration = i;
let high = data.daily.data[i].temperatureHigh;
let low = data.daily.data[i].temperatureLow;
let feels = data.daily.data[i].apparentTemperature;
let desc = data.daily.data[i].summary;
let icon = data.daily.data[i].icon;
let skycons = new Skycons({ color: "#3e606f" });
$("#card__days").html(`
<div class="card__daily">
<h2 id="daily__date"${iteration}">${date}</h2>
<canvas src="" alt="icon" class="icon" id="daily__icon${iteration}"></canvas>
<div class="degrees">
<h3 id="daily__high${iteration}" class="temp">${high}℉ / ${low}℉</h3>
</div>
<h3 id="daily__desc${iteration}">${desc}</h3>
</div>
`);
skycons.add(
document.getElementById("daily__icon" + i),
icon
);
skycons.play();
});
}
EDIT: Here is what it currently looks like and some data from the API.
Upvotes: 2
Views: 60
Reputation: 135
You only see the last card because in each iteration the for loop overwrites the html with the latest ${iteration} data, instead of creating a new piece of data and a new html element. To fix this:
As a side note, I only used insertAdjacentHTML because I needed the user to be able to create and delete these html elements, so their amount could not be predefined. In your case, it seems like you know you need exactly 7 elements. If this is the case, I would suggest to stick with html and css, and the only usage of JS would be to update a placeholder text with the newly-fetched data. Hard-coding in this case seems a bit more error-proof :)
Upvotes: 0
Reputation: 44107
If you want to make all seven cards appear, use .append()
instead:
$("#card_days").append(/* Your card HTML */);
Upvotes: 1