-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (33 loc) · 1.38 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
50
51
52
53
const apiKey = "894a1c42039b5de4a612fd58cf8ecc03";
const main = document.getElementById('main');
const form = document.getElementById('form');
const search = document.getElementById('search');
const url = (city)=> `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
async function getWeatherByLocation(city){
const resp = await fetch(url(city), {
origin: "cros" });
const respData = await resp.json();
addWeatherToPage(respData);
}
function addWeatherToPage(data){
const temp = Ktoc(data.main.temp);
const weather = document.createElement('div')
weather.classList.add('weather');
weather.innerHTML = `
<h2><img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /></h2>
<small>${data.weather[0].main}</small>
`;
// cleanup
main.innerHTML= "";
main.appendChild(weather);
};
function Ktoc(K){
return Math.floor(K - 273.15);
}
form.addEventListener('submit',(e) =>{
e.preventDefault();
const city = search.value;
if(city){
getWeatherByLocation(city)
}
});