-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
58 lines (57 loc) · 2 KB
/
app.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
54
55
56
57
58
let result = document.getElementById("result");
let searchBtn = document.getElementById("search-btn");
let cityRef = document.getElementById("city");
//Function to fetch weather details from api and display them
let getWeather = () => {
let cityValue = cityRef.value;
//If input field is empty
if (cityValue.length == 0) {
result.innerHTML = `<h3 class="msg">Please enter a city name</h3>`;
}
//If input field is NOT empty
else {
let url = `https://api.openweathermap.org/data/2.5/weather?q=${cityValue}&appid=${key}&units=metric`;
//Clear the input field
cityRef.value = "";
fetch(url)
.then((resp) => resp.json())
//If city name is valid
.then((data) => {
console.log(data);
console.log(data.weather[0].icon);
console.log(data.weather[0].main);
console.log(data.weather[0].description);
console.log(data.name);
console.log(data.main.temp_min);
console.log(data.main.temp_max);
result.innerHTML = `
<h2>${data.name}</h2>
<h4 class="weather">${data.weather[0].main}</h4>
<h4 class="desc">${data.weather[0].description}</h4>
<img src="https://openweathermap.org/img/w/${data.weather[0].icon}.png">
<h1>${data.main.temp} °</h1>
<div class="temp-container">
<div>
<h4 class="title">min</h4>
<h4 class="temp">${data.main.temp_min}°</h4>
</div>
<div>
<h4 class="title">max</h4>
<h4 class="temp">${data.main.temp_max}°</h4>
</div>
</div>
`;
})
//If city name is NOT valid
.catch(() => {
result.innerHTML = `<h3 class="msg">City not found</h3>`;
});
}
};
searchBtn.addEventListener("click", getWeather);
window.addEventListener("load", getWeather);
document.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
getWeather();
}
});