So, i am trying to add an img element from openweatherAPI, that shows an icon relative to what is found in the JSON results when the user gets the current web stats from typing a city, (i.e an image of scattered clouds, clear skies, etc). in order to display the img, i understand i need to paste the url into the "src" section of the img tag. the URL would look something like:
const png = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
however, in order to make this dynamic, the img tags "src" would have to change based on what the image file is from the typed in city.
I have the logic defined from the "icon" and "png" variables in the js file. My question is, how to i get the html img 'src' to populate with the results of my "png" variable, based on the city the user inputs on the page?
I have included both html and javasript codes below
const button = document.querySelector(".button")
const inputValue = document.querySelector(".inputValue")
const name = document.querySelector(".name")
const desc = document.querySelector(".desc")
const temp = document.querySelector(".temp")
const img = document.querySelector(".image")
button.addEventListener('click', function (){
fetch('http://api.openweathermap.org/data/2.5/weather?q='+ inputValue.value +'&units=imperial&appid=61dcc0033e94c4172d2bb94bb607fc5d')
.then(response => response.json())
.then(data => {
const nameValue = data['name']
const tempValue = data['main']['temp']
const descValue = data['weather'][0]['description']
const icon = weatherData.weather[0].icon
const png = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
name.innerHTML = nameValue
temp.innerHTML = tempValue
desc.innerHTML = descValue
img.innerHTML =
})
.catch(err => alert("Wrong City name!"))
})
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>OpenWeatherAPI</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="desc"></p>
<p class="temp"></p>
<img class="image" src="">
</div>
<script src='main.js'></script>
</body>
</html>
If I am not mistaken I do not see anywhere in your Java Script where you change the <img>
src.
EDIT
You can change the src by simply getting that element then setting it's source like blow:
document.getElementById("myImg").src = png;
This is assuming you add an id of "myImg"
to the <img>
tag like so:
<img class="image" src="" id="myImg">
EDIT 2 I did not realize you already got the element earlier on so all you need to do is:
img.src = png;