Reputation: 23
I ´m fetching from a weather api information to my app. I manage to bring and change info in my html for the "location-timezone", "temperature-degree" and "tempemperature-description"; but I´m having trouble changing mi "temperature-icon" to de api icon.
This is the section of my html I am working:
<div>
<div class="w-location">
<h6 class="location-timezone">Timezone</h6>
</div>
<div class="w-icon">
<img id="temp-icon" src="imagenes/calendar.png">
</div>
<div class="w-temperature">
<p class="temp-degree">7 ° <span>C</span></p>
<p class="col-6 temp-description"> Freezen </p>
</div>
</div>
This is my javasript where I bring the info from de api and made the functions to change info in my html:
window.addEventListener('load', () => {
let long;
let lat;
let data;
let newIcon;
let locationTimezone = document.querySelector(".location-timezone");
let tempDescription = document.querySelector(".temp-description");
let tempDegree = document.querySelector(".temp-degree");
if (navigator) {
long = -87.627778;
lat = 41.881944;
const api = `http://api.weatherapi.com/v1/current.json?
key=db5d332edd014d29aa1175108201908&q=${lat},${long}`;
fetch(api)
.then(response => {
return response.json();
})
.then(function (json) {
data = json;
//set DOM elements from the API
locationTimezone.textContent = data.location.tz_id;
tempDescription.textContent = data.current.condition.text;
tempDegree.textContent = data.current.temp_c;
newIcon = data.current.condition.icon;
})
} else {
h1.textContent = "Geolocation not working"
}
});
How can I set the newIcon information into my img (id=#temp-icon src="") in my html?
Thanks!!
Upvotes: 1
Views: 3064
Reputation: 187
You can do this with either Javascript object or by setting the existing img src.
In your case
document.getElementById("temp-icon").src = newIcon; //assuming newIcon is the URL
Or you could create a new Javascript Image object and pass the icon image source to it.
let iconImage = new Image();
iconImage.src = newIcon;
Then add/append the iconImage
object as your div's child. (w-icon
)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
Upvotes: 1