-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
53 lines (41 loc) · 1.52 KB
/
Copy pathscript.js
File metadata and controls
53 lines (41 loc) · 1.52 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
document.addEventListener('DOMContentLoaded',async() =>{
const cityInput =document.getElementById("city-input");
const getWeatherBtn =document.getElementById("get-weather-btn");
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 ="350f58769063806435e4a2660410e923";
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){
console.log(data);
const{ name,main,weather} = data;
cityNameDisplay.textContent = name;
temperatureDisplay.textContent = `Temperature : ${main.temp}`;
descriptionDisplay.textContent = `Weather : ${weather[0].description}`;
weatherInfo.classList.remove('hidden');
errorMessage.classList.add('hidden');
}
function showError(){
weatherInfo.classList.add('hidden');
errorMessage.classList.remove('hidden');
}
})