-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (44 loc) · 1.73 KB
/
index.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
58
const apikey = "363e501f35b347c4a6b8356a16eae6d2";
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";
weatherDataEl.querySelector(".details").innerHTML = "";
}
}