-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
51 lines (45 loc) · 1.78 KB
/
app.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
const searchBar = document.querySelector(".search-bar");
const searchButton = document.querySelector(".search > button");
const cityNameElement = document.querySelector(".city");
const tempElement = document.querySelector(".temp");
const iconElement = document.querySelector(".icon");
const descriptionElement = document.querySelector(".description");
const humidityElement = document.querySelector(".humidity");
const windElement = document.querySelector(".wind");
const weatherDataElem = document.querySelector(".weather");
const weather = {
apiKey: "b84459078c0bb3a4527cb234e6616f57",
async fetchWeather() {
try {
const response = await fetch(`
https://api.openweathermap.org/data/2.5/weather?q=${searchBar.value}&units=metric&appid=${this.apiKey}`);
const data = await response.json();
displayData(data);
} catch (error) {
if (!weatherDataElem.classList.contains("loading"))
weatherDataElem.classList.add("loading");
alert("No weather found!");
}
},
};
function displayData({ name, main, weather, wind }) {
document.body.style.backgroundImage = `url("https://source.unsplash.com/1600x900/?${name}")`;
cityNameElement.innerText = `Weather in ${name}`;
tempElement.innerText = `${main.temp}°C`;
iconElement.src =
"https://openweathermap.org/img/wn/" + weather[0].icon + ".png";
descriptionElement.innerText = weather[0].description;
humidityElement.innerText = `Humidity: ${main.humidity}%`;
windElement.innerText = `Wind speed: ${wind.speed} km/h`;
weatherDataElem.classList.remove("loading");
}
searchButton.addEventListener("click", () => {
weather.fetchWeather();
searchBar.value = "";
});
searchBar.addEventListener("keyup", (e) => {
if (e.key === "Enter") {
weather.fetchWeather();
searchBar.value = "";
}
});