forked from JasminHed/newjs-project-weather-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
238 lines (198 loc) · 7.63 KB
/
script.js
File metadata and controls
238 lines (198 loc) · 7.63 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
document.addEventListener('DOMContentLoaded', function () {
// API information
const API_KEY = '3bad52890d7306cc268371520cbaace6';
const BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast';
// List of default cities
const cities = ['Stockholm', 'Gothenburg', 'Oslo'];
let weeklyForecast = {};
let currentCityIndex = 0;
// Function to fetch weather data from the API
async function fetchWeather(city) {
try {
const response = await fetch(`${BASE_URL}?q=${city}&units=metric&appid=${API_KEY}`);
const data = await response.json();
if (data.cod !== "200") {
throw new Error(data.message);
}
return data;
} catch (error) {
console.error(`Error fetching weather data for ${city}:`, error);
return null;
}
}
// Function to get the day name from a date
function getDayName(dateString) {
const date = new Date(dateString);
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
}
async function fetchAndStoreWeather(city) {
const data = await fetchWeather(city);
if (!data || !data.list) {
return;
}
// Extract today's forecast
const todayData = data.list.find(entry => entry.dt_txt.includes("12:00:00")) || data.list[0];
const todayDate = todayData.dt_txt.split(" ")[0]; // Extract 'YYYY-MM-DD'
const sunriseTime = new Date(data.city.sunrise * 1000).toLocaleTimeString("sv-SE", { hour: "2-digit", minute: "2-digit" });
const sunsetTime = new Date(data.city.sunset * 1000).toLocaleTimeString("sv-SE", { hour: "2-digit", minute: "2-digit" });
// Create today's forecast object
const todayForecast = {
city: data.city.name,
day: getDayName(todayDate),
weather: todayData.weather[0].description,
icon: todayData.weather[0].icon,
temp: todayData.main.temp,
wind: todayData.wind.speed,
sunrise: sunriseTime,
sunset: sunsetTime,
};
// 4-day forecast. Group forecast entries by day to get one entry per day
const dailyForecasts = {};
data.list.forEach(entry => {
const date = entry.dt_txt.split(' ')[0];
const hour = entry.dt_txt.split(' ')[1].split(':')[0];
// Use noon (12:00) forecasts for consistency
if (hour === '12') {
// Skip today's date
if (date !== todayDate) {
dailyForecasts[date] = {
date: date,
day: getDayName(date),
icon: entry.weather[0].icon,
weather: entry.weather[0].description,
temp: entry.main.temp,
wind: entry.wind.speed,
};
}
}
});
// Convert to array and take the first 4 days
const upcomingForecast = Object.values(dailyForecasts).slice(0, 4);
// Store forecasts
weeklyForecast[city] = {
today: todayForecast,
upcoming: upcomingForecast
};
// Store in localStorage for persistence
localStorage.setItem("weatherData", JSON.stringify(weeklyForecast));
// Update UI
displayTodaysWeather(todayForecast);
displayWeeklyWeather(upcomingForecast);
// Set background based on weather
updateBackground(todayForecast.weather, todayForecast.icon);
}
// Function to display today's weather in the UI
function displayTodaysWeather(forecast) {
const weatherContent = document.getElementById('weather-content');
if (!weatherContent) return;
// Create HTML with the OpenWeatherMap icon
weatherContent.innerHTML = `
<div class="weather-icon">
<div class="icon-temp">
<p id="temperature">${Math.round(forecast.temp)}°C</p>
<img id="main-icon" src="https://openweathermap.org/img/wn/${forecast.icon}@2x.png" alt="${forecast.weather}">
</div>
<div>
<p id="city">${forecast.city}</p>
<p id="weather">${forecast.weather}</p>
</div>
<div class="sunrise-sunset">
<p id="sunrise">Sunrise ${forecast.sunrise}</p>
<p id="sunset">Sunset ${forecast.sunset}</p>
</div>
</div>
`;
}
// Function to display the weekly forecast in the UI
function displayWeeklyWeather(forecastList) {
const forecastTable = document.querySelector("#weather-forecast table");
if (!forecastTable) return;
const rows = forecastTable.getElementsByTagName("tr");
if (!rows || rows.length === 0) return;
forecastList.forEach((forecast, index) => {
if (index < rows.length) {
// Update day
const dayCell = rows[index].querySelector(`#day${index + 1}`);
if (dayCell) {
dayCell.textContent = forecast.day;
}
// Update icon using OpenWeatherMap icon
const iconCell = rows[index].querySelector(`#iconday${index + 1}`);
if (iconCell) {
iconCell.innerHTML = `<img src="https://openweathermap.org/img/wn/${forecast.icon}.png" alt="${forecast.weather}">`;
}
// Update temp and wind
const tempCell = rows[index].querySelector(`#tempday${index + 1}`);
if (tempCell) {
tempCell.textContent = `${Math.round(forecast.temp)}°C`;
}
const windCell = rows[index].querySelector(`#windday${index + 1}`);
if (windCell) {
windCell.textContent = `${forecast.wind} m/s`;
}
}
});
}
// Function to update the background based on weather conditions
function updateBackground(weatherDescription, iconCode) {
const container = document.querySelector('.container');
if (!container) return;
// Remove previous weather classes
container.classList.remove('rainy', 'cloudy', 'clear', 'snowy', 'daytime', 'nighttime');
// Determine if it's day or night from the icon code (ends with d for day, n for night)
const isDaytime = iconCode.endsWith('d');
container.classList.add(isDaytime ? 'daytime' : 'nighttime');
// Add appropriate weather class
if (weatherDescription.includes('rain') || weatherDescription.includes('drizzle')) {
container.classList.add('rainy');
} else if (weatherDescription.includes('cloud')) {
container.classList.add('cloudy');
} else if (weatherDescription.includes('clear')) {
container.classList.add('clear');
} else if (weatherDescription.includes('snow')) {
container.classList.add('snowy');
}
}
// Function to cycle through default cities
function cycleCity() {
currentCityIndex = (currentCityIndex + 1) % cities.length;
const city = cities[currentCityIndex];
fetchAndStoreWeather(city);
}
// Event listeners
function initializeEventListeners() {
const searchButton = document.getElementById("search-button");
const inputField = document.getElementById("input-field");
const nextSideButton = document.getElementById('next-side-button');
if (searchButton) {
searchButton.addEventListener("click", function () {
if (inputField && inputField.value.trim()) {
fetchAndStoreWeather(inputField.value.trim());
}
});
}
if (inputField) {
inputField.addEventListener("keydown", function (event) {
if (event.key === "Enter" && inputField.value.trim()) {
fetchAndStoreWeather(inputField.value.trim());
}
});
}
if (nextSideButton) {
nextSideButton.addEventListener('click', cycleCity);
} else {
console.error("Could not find button with ID 'next-side-button'");
}
}
initializeEventListeners();
fetchAndStoreWeather("Stockholm");
const savedData = localStorage.getItem("weatherData");
if (savedData) {
try {
weeklyForecast = JSON.parse(savedData);
} catch (e) {
console.error("Failed to parse saved weather data:", e);
}
}
});