-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
51 lines (37 loc) · 1.31 KB
/
index.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
const apikey = "a9126b7b0582baa918da27d1e74dd4ac";
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: "cors" });
const respData = await resp.json();
console.log(respData);
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>
<br/>
<small>Current Humidity : ${data.main.humidity}</small>
`;
// cleanup
main.innerHTML = "";
main.appendChild(weather);
}
//kelvin to celsius conversion
function KtoC(K) {
return Math.floor(K - 273.15);
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const city = search.value;
if (city) {
getWeatherByLocation(city);
}
});