-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
75 lines (65 loc) · 2.84 KB
/
weather.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const URL_BASE = `https://goweather.herokuapp.com/weather`;
const search = document.getElementById("search");
const btn = document.getElementById("btn");
const Fullname = document.getElementById("name");
const main1 = document.getElementById("main-container1");
const main2 = document.getElementById("main-container2");
const main3 = document.getElementById("main-container3");
const main4 = document.getElementById("main-container4");
btn.addEventListener("click", (event) => {
event.preventDefault();
const city = search.value.trim();
if (city === '') {
alert("Please enter a city name!");
} else {
console.log(city);
const URL = `${URL_BASE}/${city.toLowerCase()}`;
let p = document.createElement("p");
p.innerText = `${city}`;
Fullname.append(p);
console.log(p);
console.log(URL);
fetch(URL)
.then(response => response.json())
.then(data => {
console.log(data);
main1.innerHTML = '';
main2.innerHTML = '';
main3.innerHTML = '';
main4.innerHTML = '';
// Display current weather in main1
const currentWeather = `
<p>Temperature: ${data.temperature || "N/A"}</p>
<p>Wind: ${data.wind || "N/A"}</p>
<p>Description: ${data.description || "N/A"}</p>`;
main1.innerHTML = currentWeather;
// Display forecast data in main2, main3, and main4
const forecast = data.forecast;
if (forecast && forecast.length >= 3) {
const day1 = forecast[0];
const day2 = forecast[1];
const day3 = forecast[2];
main2.innerHTML = `
<h3>Day ${day1.day}</h3>
<p>Temperature: ${day1.temperature}</p>
<p>Wind: ${day1.wind}</p>`;
main3.innerHTML = `
<h3>Day ${day2.day}</h3>
<p>Temperature: ${day2.temperature}</p>
<p>Wind: ${day2.wind}</p>`;
main4.innerHTML = `
<h3>Day ${day3.day}</h3>
<p>Temperature: ${day3.temperature}</p>
<p>Wind: ${day3.wind}</p>`;
} else {
const errorMsg = `<p>Forecast data is not available for the next 3 days.</p>`;
main2.innerHTML = errorMsg;
main3.innerHTML = errorMsg;
main4.innerHTML = errorMsg;
}
})
.catch(error => {
console.error("Error fetching data:", error);
});
}
});