'How to stop the Api icon keep adding when click the buttons?
I have to create a web with two buttons to show each city's information.
When I clicked the button the icon would keep adding every each time i click it.
I have tried if statement also but it did not work. is there any ways can stop it or other method to show the icon?
window.onload=function(){
var chooseBox = document.getElementById("output");
var tempOut = document.getElementById("temperature");
var condiOut = document.getElementById("conditions");
var locationOut = document.getElementById("location");
var weaIcon = document.getElementById("icon");
var torontBtn = document.getElementById("Toronto");
var tpeBtn = document.getElementById("Taipei");
var feelstemp = document.getElementById("feelsLike");
const myApiKey = "0730ce4dd97d237ff76898a994164939";
const toUrl = "https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=" + myApiKey + "&units=metric";
const tpeUrl ="https://api.openweathermap.org/data/2.5/weather?q=Taipei&appid=" + myApiKey + "&units=metric";
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if ( xhr.readyState === 4 ){
if ( xhr.status === 200){
const data = xhr.response;
console.log(data);
const iconWea = "https://openweathermap.org/img/wn/" + data.weather[0].icon + ".png";
var elementIcon = document.createElement('img');
elementIcon.setAttribute('src', iconWea);
weaIcon.appendChild(elementIcon); //SHOWASSIGNED ICON
locationOut.innerHTML = data.name;
tempOut.innerHTML = data.main.temp + "°C" ;
feelstemp.innerHTML = data.main.feels_like + "°C" ;
condiOut.innerHTML = data.weather[0].description;
} else {
locationOut.innerHTML = "API call was unsucessful";
console.log(xhr.status);
}
}
}
torontBtn.onclick = function() {
chooseBox.style.display = "block";
xhr.open('GET',toUrl,true);
xhr.responseType = 'json';
xhr.send(null);
}
tpeBtn.onclick = function () {
chooseBox.style.display = "block";
xhr.open('GET',tpeUrl,true);
xhr.responseType = 'json';
xhr.send(null);
}
};
Solution 1:[1]
This is what I did:
var iconUrl = "https://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png";
out_icon.innerHTML = `<img src='${iconUrl}'/>`;
Solution 2:[2]
weaIcon.appendChild(elementIcon) should be replaced with weaIcon.innerHtml=elementIcon
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bbsnax |
| Solution 2 | Muhammad Usama |
