-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
38 lines (32 loc) · 1.23 KB
/
script.js
File metadata and controls
38 lines (32 loc) · 1.23 KB
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
let input = document.querySelector(".input-box input");
let humidity = document.querySelector(".humidity-value");
let speed = document.querySelector(".speed-value");
let searchBtn = document.querySelector(".search-btn");
let temperature = document.querySelector(".temp-value");
const apikey = "enter your api key";
searchBtn.addEventListener("click", async () => {
let city = input.value.trim(); // Get the current input value
if (city === "") {
alert("Enter a valid city");
return;
}
try {
await checkWeather(city); // Call the function with the current city
} catch (error) {
console.error(error);
alert("City not found or API request failed.");
}
});
async function checkWeather(city) {
const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}&units=metric`;
let response = await fetch(URL);
if (!response.ok) {
throw new Error("City not found or bad request");
}
let data = await response.json();
console.log(data);
// Update the DOM with fetched weather data
humidity.textContent = `${data.main.humidity} %`;
speed.textContent = `${data.wind.speed} km/h`;
temperature.textContent = `${data.main.temp} °C`;
}