-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
91 lines (79 loc) · 2.54 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const inputBox = document.querySelector(".input-box");
const searchBtn = document.getElementById("searchBtn");
const weather_img = document.querySelector(".weather-img");
const temperature = document.querySelector(".temperature");
const description = document.querySelector(".description");
const humidity = document.getElementById("humidity");
const wind_speed = document.getElementById("wind-speed");
const location_not_found = document.querySelector(".location-not-found");
const weather_body = document.querySelector(".weather-body");
const imgBg = document.querySelector(".img-bg");
async function checkWeather(city) {
const api_key = "6c47fe18c95cff42c36fa5f35aee15a4";
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}`;
const weather_data = await fetch(`${url}`).then((response) =>
response.json()
);
if (weather_data.cod === `404`) {
location_not_found.style.display = "flex";
weather_body.style.display = "none";
console.log("error");
return;
}
console.log("run");
location_not_found.style.display = "none";
weather_body.style.display = "flex";
temperature.innerHTML = `${Math.round(weather_data.main.temp - 273.15)}°C`;
description.innerHTML = `${weather_data.weather[0].description}`;
humidity.innerHTML = `${weather_data.main.humidity}%`;
wind_speed.innerHTML = `${weather_data.wind.speed} m/s`;
switch (weather_data.weather[0].main) {
case "Clouds":
weather_img.src = "images/cloud.png";
changeBackground("cloudy");
break;
case "Clear":
weather_img.src = "images/clear.png";
changeBackground("clear");
break;
case "Rain":
weather_img.src = "images/rain.png";
changeBackground("rainy");
break;
case "Mist":
weather_img.src = "images/mist.png";
changeBackground("misty");
break;
case "Snow":
weather_img.src = "images/snow.png";
changeBackground("snowy");
break;
}
console.log(weather_data);
}
function changeBackground(condition) {
let bgImage = "";
switch (condition) {
case "clear":
bgImage = "images/clear-sky.jpg";
break;
case "cloudy":
bgImage = "images/cloudy.jpg";
break;
case "rainy":
bgImage = "images/rainy.jpg";
break;
case "misty":
bgImage = "images/misty.jpg";
break;
case "snowy":
bgImage = "images/snowy.jpg";
break;
default:
bgImage = "images/default.jpg";
}
imgBg.src = bgImage;
}
searchBtn.addEventListener("click", () => {
checkWeather(inputBox.value);
});