-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (56 loc) · 2.13 KB
/
Copy pathscript.js
File metadata and controls
70 lines (56 loc) · 2.13 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
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
const apiKey = "0a68a44998c012a0128408d3730ab99e";
// const apiKey="9400701049f6100c65a5c111911ac7c8";
const searchBtn = document.getElementById("searchBtn");
const cityInput = document.getElementById("cityInput");
const weatherCard = document.getElementById("weatherCard");
const loading = document.getElementById("loading");
const errorDiv = document.getElementById("error");
searchBtn.addEventListener("click", getWeather);
cityInput.addEventListener("keypress", function(e) {
if (e.key === "Enter") {
getWeather();
}
});
async function getWeather() {
const city = cityInput.value.trim();
if (city === "") {
showError("Please enter a city name.");
return;
}
loading.classList.remove("hidden");
weatherCard.classList.add("hidden");
errorDiv.classList.add("hidden");
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
);
if (!response.ok) {
throw new Error("City not found");
}
const data = await response.json();
displayWeather(data);
} catch (error) {
showError("City not found. Please try again.");
} finally {
loading.classList.add("hidden");
}
}
function displayWeather(data) {
document.getElementById("cityName").innerText = data.name;
document.getElementById("temperature").innerText =
`🌡 Temperature: ${data.main.temp} °C`;
document.getElementById("description").innerText =
`☁ Condition: ${data.weather[0].description}`;
document.getElementById("humidity").innerText =
`💧 Humidity: ${data.main.humidity}%`;
document.getElementById("wind").innerText =
`🌬 Wind Speed: ${data.wind.speed} m/s`;
const iconCode = data.weather[0].icon;
document.getElementById("weatherIcon").src =
`https://openweathermap.org/img/wn/${iconCode}@2x.png`;
weatherCard.classList.remove("hidden");
}
function showError(message) {
errorDiv.innerText = message;
errorDiv.classList.remove("hidden");
}