-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
59 lines (49 loc) · 1.87 KB
/
Copy pathscript.js
File metadata and controls
59 lines (49 loc) · 1.87 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
document.getElementById('searchButton')
.addEventListener('click', fetchWeather);
function fetchWeather() {
const city = document.getElementById('cityInput').value;
if (city.trim() === '') {
document.getElementById('weatherDisplay')
.innerText = 'Please enter a city name.';
return; }
document.getElementById('loading')
.style.display = 'block';
document.getElementById('weatherDisplay')
.innerHTML = '';
const url = 'https://api.openweathermap.org/data/2.5/weather?q='
+ city + '&appid=' + apiKey + '&units=metric';
fetch(url)
.then(function(response)
{ if (response.ok)
{ return response.json();
} else { document.getElementById('weatherDisplay')
.innerText = 'City not found.';
document.getElementById('loading')
.style.display = 'none'; }
})
.then(function(data)
{ if (!data)
return; displayWeather(data);
document.getElementById('loading')
.style.display = 'none'; })
.catch(function()
{ document.getElementById('weatherDisplay')
.innerText = 'Something went wrong.';
document.getElementById('loading')
.style.display = 'none'; });
}
function displayWeather(data)
{ const weatherDisplay = document.getElementById('weatherDisplay');
const temperature = data.main.temp;
const humidity = data.main.humidity;
const description = data.weather[0].description;
weatherDisplay.innerHTML =
'<p>Temperature: '
+ temperature
+ '°C</p>'
+ '<p>Humidity: '
+ humidity + '%</p>'
+ '<p>Condition: '
+ description
+ '</p>';
}