-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
72 lines (56 loc) · 2.09 KB
/
script.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"use strict";
const apikey = "35de801035467dcb899bac4c3339aea6";
const weatherDataEl = document.getElementById("weather-data");
const cityInputEl = document.getElementById("city-input");
const formEl = document.querySelector("form");
formEl.addEventListener("submit", (event) => {
// preventing reload on btn click
event.preventDefault();
// storing input value
const cityValue = cityInputEl.value;
console.log(cityValue);
getWeatherData(cityValue);
});
async function getWeatherData(cityValue) {
try {
// fetched data for specific city/nation
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");
}
// converted data to json format to use in site
const data = await response.json();
// getting the data I need
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)}°C`,
`Humidity: ${data.main.humidity}%`,
`wind speed: ${data.wind.speed} m/s`,
];
console.log(details);
console.log(description);
console.log(temperature);
// Replacing With Realtime Data
weatherDataEl.querySelector(".icon").innerHTML = `<img
src="https://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 = "";
}
}