-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
32 lines (28 loc) · 1.1 KB
/
script.js
File metadata and controls
32 lines (28 loc) · 1.1 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
const apiKey = "cc3d8ab38e87e89d131c7a2100016cd0"; // Get it free from https://openweathermap.org/
document.getElementById("searchBtn").addEventListener("click", () => {
const city = document.getElementById("cityInput").value;
if (city) {
getWeather(city);
} else {
alert("Please enter a city name!");
}
});
async function getWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error("City not found");
}
const data = await response.json();
document.getElementById("weatherResult").innerHTML = `
<h2>${data.name}, ${data.sys.country}</h2>
<p>🌡️ Temperature: ${data.main.temp}°C</p>
<p>☁️ Weather: ${data.weather[0].description}</p>
<p>💧 Humidity: ${data.main.humidity}%</p>
<p>🌬️ Wind Speed: ${data.wind.speed} m/s</p>
`;
} catch (error) {
document.getElementById("weatherResult").innerHTML = `<p style="color:red;">${error.message}</p>`;
}
}