-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
358 lines (262 loc) · 11.8 KB
/
Copy pathscript.js
File metadata and controls
358 lines (262 loc) · 11.8 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
document.addEventListener('DOMContentLoaded', () => {
const searchForm = document.querySelector('#search-form');
const searchInput = document.querySelector('#search-input');
const cityNameElement = document.querySelector('#city-name');
const historyDropdown = document.querySelector('#history-dropdown');
const alertElement = document.getElementById('weather-alert');
const alertText = alertElement.querySelector('span');
const closeAlertButton = document.getElementById('close-alert');
const API_KEY = '36324a6b4a3a650821d18ca766b5d142';
const HISTORY_KEY = 'weatherAppHistory';
searchForm.addEventListener('submit', (event) => {
event.preventDefault();
const cityName = searchInput.value.trim();
if (cityName) {
fetchWeatherByCity(cityName);
historyDropdown.classList.remove('visible'); // Hide after search
searchForm.reset();
}
});
//drop down
searchInput.addEventListener('click', (event) => {
event.stopPropagation(); // Stop click from bubbling to the window
// Only show if there's history
if (getHistory().length > 0) {
historyDropdown.classList.add('visible');
}
});
//Hide dropdown if user clicks anywhere else
window.addEventListener('click', () => {
historyDropdown.classList.remove('visible');
});
//closes the alert on extreme temp.
closeAlertButton.addEventListener('click', () => {
alertElement.classList.remove('show');
});
addAccordionLogic();
loadInitialWeather();
updateHistoryDropdown(getHistory());
function loadInitialWeather() {
const defaultCity = 'London';
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
fetchWeatherByCoords(lat, lon);
},
(error) => {
console.warn("Geolocation failed. Fetching default city.");
fetchWeatherByCity(defaultCity);
}
);
} else {
console.warn("Geolocation not supported. Fetching default city.");
fetchWeatherByCity(defaultCity);
}
}
async function fetchWeatherByCity(city) {
const apiUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${API_KEY}&units=metric`;
await getWeatherData(apiUrl);
}
async function fetchWeatherByCoords(lat, lon) {
const apiUrl = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
await getWeatherData(apiUrl);
}
async function getWeatherData(apiUrl) {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
console.error('Location not found.');
cityNameElement.textContent = 'Location not found';
return;
}
// On successful search, save the city name and update dropdown
const data = await response.json();
console.log(data);
const newCityName = data.city.name;
const updatedHistory = saveHistory(newCityName);
updateHistoryDropdown(updatedHistory);
updateUI(data);
} catch (error) {
console.error('Error fetching weather:', error);
cityNameElement.textContent = 'Error fetching weather';
}
}
function updateUI(data) {
cityNameElement.textContent = data.city.name;
const allDailyForecasts = processForecastData(data.list);
const now = new Date();
const cityLocalDate = new Date(now.getTime() + (data.city.timezone * 1000));
const localYear = cityLocalDate.getUTCFullYear();
const localMonth = String(cityLocalDate.getUTCMonth() + 1).padStart(2, '0');
const localDay = String(cityLocalDate.getUTCDate()).padStart(2, '0');
const localDateString = `${localYear}-${localMonth}-${localDay}`;
console.log("City's local date:", localDateString);
let todayDataIndex = allDailyForecasts.findIndex(day => day.date === localDateString);
if (todayDataIndex === -1) {
console.warn("Could not find matching date for today. Defaulting to first item.");
todayDataIndex = 0;
}
// --- 4. Updating the "Today" Card ---
const todayData = allDailyForecasts[todayDataIndex];
const todayCard = document.querySelector('.accordion--item.today');
updateCard(todayCard, todayData, 'Today');
// 1. Getting today's max temperature
const todayMaxTemp = Math.round(todayData.maxTemp);
// 2. Checking if it's over 40
if (todayMaxTemp > 40) {
// heat warning message
alertText.innerHTML = `🔥 <strong>Heat Warning:</strong> Temperature may reach ${todayMaxTemp}°C. Stay hydrated!`;
// Adding .show class to make it slide down
alertElement.classList.add('show');
// Removing .cold class to make sure it's red
alertElement.classList.remove('cold');
// 3. Checking if it's below 0
} else if (todayMaxTemp < 0) {
// cold warning message
alertText.innerHTML = `❄️ <strong>Cold Warning:</strong> Temperature may drop to ${todayMaxTemp}°C. Bundle up!`;
// Adding .show to make it slide down and .cold to make it blue
alertElement.classList.add('show', 'cold');
// 4. Otherwise (if temp is normal)
} else {
// Remove .show to hide the bar
alertElement.classList.remove('show');
}
// --- 5. Updating the 5-Day Forecast Cards ---
const forecastCards = document.querySelectorAll('.accordion--item:not(.today)');
// Getting the *rest* of the items *after* today
const next5Days = allDailyForecasts.slice(todayDataIndex + 1, todayDataIndex + 6);
next5Days.forEach((dayData, index) => {
if (forecastCards[index]) {
const card = forecastCards[index];
const dayName = getDayOfWeek(dayData.date);
updateCard(card, dayData, dayName);
}
});
}
//drop down logic
function getHistory(){
const rawHistory =localStorage.getItem(HISTORY_KEY);
if(rawHistory){
return JSON.parse(rawHistory);
}
else{
return [];
}
}
function saveHistory(newCity){
let history =getHistory();
history = history.filter(city => city.toLowerCase() !== newCity.toLowerCase());
history.unshift(newCity);
history= history.slice(0,3);
localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
return history;
}
function updateHistoryDropdown(history) {
historyDropdown.innerHTML = '';
if (history.length === 0) {
return;
}
history.forEach(city => {
const li = document.createElement('li');
li.textContent = city;
// Add click event to search for this city
li.addEventListener('click', (event) => {
event.stopPropagation();
searchInput.value = city;
fetchWeatherByCity(city);
historyDropdown.classList.remove('visible');
searchForm.reset();
});
historyDropdown.appendChild(li);
});
}
function updateCard(cardElement, data, dayName) {
// Getting date and format it (e.g., 10/28)
const dateObj = new Date(data.dt_txt || data.date);
const formattedDate = `${dateObj.getMonth() + 1}/${dateObj.getDate()}`;
// Getting values, rounding them
const maxTemp = Math.round(data.main?.temp_max ?? data.maxTemp);
const minTemp = Math.round(data.main?.temp_min ?? data.minTemp);
const description = data.weather?.[0]?.description ?? data.description;
const windSpeed = Math.round(data.wind?.speed ?? data.windSpeed);
const humidity = Math.round(data.main?.humidity ?? data.humidity);
const rainChance = Math.round((data.pop || 0) * 100);
// Update all elements *inside* the card
cardElement.querySelector('.day-name').textContent = dayName;
cardElement.querySelector('.numdate').textContent = formattedDate;
cardElement.querySelector('.weather-description').textContent = description;
cardElement.querySelectorAll('.max-temp').forEach(el => el.textContent = maxTemp);
cardElement.querySelectorAll('.min-temp').forEach(el => el.textContent = minTemp);
cardElement.querySelector('.wind-speed').textContent = windSpeed;
cardElement.querySelector('.humidity').textContent = humidity;
cardElement.querySelector('.rain-chance').textContent = rainChance;
}
function processForecastData(forecastList) {
const dailyData = {};
// Starting at i=1 to skip "Today's" forecast
for (let i = 1; i < forecastList.length; i++) {
const forecast = forecastList[i];
const date = forecast.dt_txt.split(' ')[0]; // Get 'YYYY-MM-DD'
if (!dailyData[date]) {
dailyData[date] = {
date: date,
maxTemp: -Infinity,
minTemp: Infinity,
humidity: 0,
windSpeed: 0,
pop: 0,
description: '',
icon: '',
count: 0,
};
}
const day = dailyData[date];
day.maxTemp = Math.max(day.maxTemp, forecast.main.temp_max);
day.minTemp = Math.min(day.minTemp, forecast.main.temp_min);
day.humidity += forecast.main.humidity;
day.windSpeed += forecast.wind.speed;
day.pop += forecast.pop;
day.count++;
if (forecast.dt_txt.includes("15:00:00")) {
day.description = forecast.weather[0].description;
day.icon = forecast.weather[0].icon;
}
}
const processedList = Object.values(dailyData).map(day => {
day.humidity = day.humidity / day.count;
day.windSpeed = day.windSpeed / day.count;
day.pop = day.pop / day.count;
if (!day.description) {
const firstForecastForDay = forecastList.find(f => f.dt_txt.startsWith(day.date));
if(firstForecastForDay) {
day.description = firstForecastForDay.weather[0].description;
day.icon = firstForecastForDay.weather[0].icon;
}
}
return day;
});
return processedList;
}
function getDayOfWeek(dateString) {
const date = new Date(dateString);
const options = { weekday: 'long', timeZone: 'UTC' };
return date.toLocaleString('en-US', options);
}
function addAccordionLogic() {
// Selecting only the main <li> items
const allItems = document.querySelectorAll('.accordion--item');
allItems.forEach(item => {
item.addEventListener('click', () => {
if (item.classList.contains('opened')) {
return;
}
allItems.forEach(otherItem => {
otherItem.classList.remove('opened');
});
item.classList.add('opened');
});
});
}
});