-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
49 lines (41 loc) · 1.75 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
document.addEventListener("DOMContentLoaded", () => {
const getWeatherBtn = document.getElementById("get-weather-btn");
const cityInput = document.getElementById("city-input");
const weatherInfo = document.getElementById("weather-info");
const cityNameDisplay = document.getElementById("city-name");
const temperatureDisplay = document.getElementById("temperature");
const descriptionDisplay = document.getElementById("description");
const errorMessage = document.getElementById("error-message");
const API_KEY = "58f83ef8715d6d6df9ca2e167055106f"; // env variables
getWeatherBtn.addEventListener('click', async () => {
const city = cityInput.value.trim();
if (!city) return;
try {
const weatherData = await fetchWeatherData(city);
displayWeatherData(weatherData);
} catch (error) {
showError();
}
});
async function fetchWeatherData(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error("City not found");
}
const data = await response.json();
return data;
}
function displayWeatherData(data) {
const { name, main, weather } = data;
cityNameDisplay.textContent = name;
temperatureDisplay.textContent = `Temperature: ${main.temp}°C`;
descriptionDisplay.textContent = `Weather: ${weather[0].description}`;
weatherInfo.classList.remove('hidden');
errorMessage.classList.add('hidden');
}
function showError() {
weatherInfo.classList.add('hidden');
errorMessage.classList.remove('hidden');
}
});