-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
67 lines (60 loc) · 2.62 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
const apiUrl = "/.netlify/functions/weather"; // Call your serverless function endpoint
const searchBox = document.querySelector(".search input");
const searchBtn = document.querySelector(".search button");
const weatherIcon = document.querySelector(".weather-icon");
async function checkWeather(city) {
const errorElement = document.querySelector(".error");
const weatherElement = document.querySelector(".weather");
if (!city) {
errorElement.textContent = "Please enter a city name.";
errorElement.style.display = "block";
weatherElement.style.display = "none";
return;
}
try {
const response = await fetch(`${apiUrl}?city=${city}`);
if (!response.ok) {
const message = response.status === 404 ? "Invalid city name" : "Error fetching data";
errorElement.textContent = message;
errorElement.style.display = "block";
weatherElement.style.display = "none";
} else {
const data = await response.json();
// Update UI with weather data
document.querySelector(".city").innerHTML = data.name;
document.querySelector(".temp").innerHTML = Math.round(data.main.temp) + "°c";
document.querySelector(".humidity").innerHTML = data.main.humidity + "%";
document.querySelector(".wind").innerHTML = data.wind.speed + "km/h";
// Update weather icon based on weather condition
switch (data.weather[0].main) {
case "Clouds":
weatherIcon.src = "images/cloud.png";
break;
case "Clear":
weatherIcon.src = "images/clear.png";
break;
case "Rain":
weatherIcon.src = "images/rain.png";
break;
case "Drizzle":
weatherIcon.src = "images/drizzle.png";
break;
case "Mist":
weatherIcon.src = "images/mist.png";
break;
default:
weatherIcon.src = "images/default.png"; // Fallback image
}
weatherElement.style.display = "block";
errorElement.style.display = "none";
}
} catch (error) {
errorElement.textContent = "An error occurred while fetching the weather data.";
errorElement.style.display = "block";
weatherElement.style.display = "none";
}
}
searchBtn.addEventListener("click", () => {
checkWeather(searchBox.value);
searchBox.value = ""; // Clear the input field after searching
});