-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweatherApp.js
58 lines (37 loc) · 1.86 KB
/
weatherApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const apikey = "8246328328cd4dd51322791d82ac7106";
const weatherDataEl = document.getElementById("weather-data");
const cityInputEl = document.getElementById("city-input");
const formEl = document.querySelector("form")
formEl.addEventListener("submit",(event) => {
event.preventDefault();
const cityValue = cityInputEl.value;
getWeatherData(cityValue);
});
async function getWeatherData(cityValue) {
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityValue}&appid=${apikey}&units=metric`
);
if(!response.ok) {
throw new Error("network response was not ok")
}
const data = await response.json();
const temperature = Math.round(data.main.temp);
const description = data.weather[0].description;
const icon = data.weather[0].icon;
const details = [
`Feels like: ${Math.round(data.main.feels_like)}`,
`Humidity: ${data.main.humidity}%`,
`Wind speed: ${data.wind.speed} m/s`
]
weatherDataEl.querySelector(".icon").innerHTML = `<img src="http://openweathermap.org/img/wn/${icon}.png" alt="Weather Icon">`;
weatherDataEl.querySelector(".temperature").textContent = `${temperature}°C`;
weatherDataEl.querySelector(".description").textContent = `${description}`;
weatherDataEl.querySelector(".details").innerHTML = details.map((detail) => `<div>${detail}</div>`
).join("");
} catch (error) {
weatherDataEl.querySelector(".icon").innerHTML = ``;
weatherDataEl.querySelector(".temperature").textContent = ``;
weatherDataEl.querySelector(".description").textContent = "An error happened, please try again later (or) check your spelling";
weatherDataEl.querySelector(".details").innerHTML = "";
}
}