-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
306 lines (253 loc) · 10.8 KB
/
script.js
File metadata and controls
306 lines (253 loc) · 10.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
// --- OpenWeatherMap API Key ---
// Go to https://home.openweathermap.org/users/sign_up to get a free API key.
// IMPORTANT: Replace the placeholder below with your actual API key to fetch real data.
const API_KEY = '3a37214012a79559d32386ff316f7c3b';
// DOM Elements
const cityInput = document.getElementById('city-input');
const suggestionsList = document.getElementById('suggestions-list');
const locationBtn = document.getElementById('location-btn');
const themeToggle = document.getElementById('theme-toggle');
const themeIcon = document.getElementById('theme-icon');
// State Elements
const introState = document.getElementById('intro');
const loadingState = document.getElementById('loading');
const errorState = document.getElementById('error');
const errorMessage = document.getElementById('error-message');
const weatherDashboard = document.getElementById('weather-dashboard');
// Weather Data Elements
const cityNameEl = document.getElementById('city-name');
const currentDateEl = document.getElementById('current-date');
const weatherIconEl = document.getElementById('weather-icon');
const temperatureEl = document.getElementById('temperature');
const weatherConditionEl = document.getElementById('weather-condition');
const humidityEl = document.getElementById('humidity');
const windSpeedEl = document.getElementById('wind-speed');
const feelsLikeEl = document.getElementById('feels-like');
const pressureEl = document.getElementById('pressure');
const forecastContainer = document.getElementById('forecast-container');
// Base URLs
const WEATHER_BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';
const FORECAST_BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast';
const GEOCODING_BASE_URL = 'https://api.openweathermap.org/geo/1.0/direct';
// --- Theme Management ---
// Initialize theme
const currentTheme = localStorage.getItem('theme') || 'light';
if (currentTheme === 'dark') {
document.body.classList.add('dark-mode');
themeIcon.textContent = 'light_mode';
}
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
if (document.body.classList.contains('dark-mode')) {
themeIcon.textContent = 'light_mode';
localStorage.setItem('theme', 'dark');
} else {
themeIcon.textContent = 'dark_mode';
localStorage.setItem('theme', 'light');
}
});
// --- Event Listeners ---
// --- Event Listeners ---
let typingTimer;
const doneTypingInterval = 500; // Delay in ms to wait after typing stops
cityInput.addEventListener('input', (e) => {
clearTimeout(typingTimer);
const query = e.target.value.trim();
if (query.length >= 2) {
typingTimer = setTimeout(() => {
fetchCitySuggestions(query);
}, doneTypingInterval);
} else {
suggestionsList.classList.add('hidden');
suggestionsList.innerHTML = '';
}
});
cityInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const city = cityInput.value.trim();
if (city) {
suggestionsList.classList.add('hidden');
getWeatherData(city);
cityInput.blur(); // dismiss keyboard on mobile
}
}
});
// Close suggestions when clicking outside
document.addEventListener('click', (e) => {
if (!cityInput.contains(e.target) && !suggestionsList.contains(e.target)) {
suggestionsList.classList.add('hidden');
}
});
locationBtn.addEventListener('click', () => {
if (navigator.geolocation) {
showLoading();
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
getWeatherByCoords(latitude, longitude);
},
(err) => {
showError('Geolocation permission denied or unavailable. Please search for a city manually.');
}
);
} else {
showError('Geolocation is not supported by your browser.');
}
});
// --- API Fetching ---
async function getWeatherData(city) {
showLoading();
try {
const weatherUrl = `${WEATHER_BASE_URL}?q=${city}&appid=${API_KEY}&units=metric`;
const forecastUrl = `${FORECAST_BASE_URL}?q=${city}&appid=${API_KEY}&units=metric`;
await fetchAndDisplay(weatherUrl, forecastUrl);
} catch (error) {
showError(error.message);
}
}
async function getWeatherByCoords(lat, lon) {
showLoading();
try {
const weatherUrl = `${WEATHER_BASE_URL}?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
const forecastUrl = `${FORECAST_BASE_URL}?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
await fetchAndDisplay(weatherUrl, forecastUrl);
} catch (error) {
showError(error.message);
}
}
async function fetchAndDisplay(weatherUrl, forecastUrl) {
try {
if (API_KEY === 'YOUR_API_KEY_HERE') {
throw new Error('API Key is missing. Please add your OpenWeatherMap API Key in script.js.');
}
const [weatherResponse, forecastResponse] = await Promise.all([
fetch(weatherUrl),
fetch(forecastUrl)
]);
const weatherData = await weatherResponse.json();
const forecastData = await forecastResponse.json();
if (!weatherResponse.ok) {
throw new Error(weatherData.message || 'City not found.');
}
updateCurrentWeather(weatherData);
updateForecast(forecastData);
updateDynamicBackground(weatherData.weather[0].main);
showDashboard();
} catch (error) {
showError(error.message);
}
}
async function fetchCitySuggestions(query) {
try {
const geoUrl = `${GEOCODING_BASE_URL}?q=${query}&limit=5&appid=${API_KEY}`;
const response = await fetch(geoUrl);
if (!response.ok) throw new Error('Failed to fetch suggestions');
const data = await response.json();
if (data.length > 0) {
renderSuggestions(data);
} else {
suggestionsList.classList.add('hidden');
}
} catch (error) {
console.error('Error fetching city suggestions:', error);
}
}
// --- UI Updating ---
function renderSuggestions(cities) {
suggestionsList.innerHTML = '';
cities.forEach(city => {
const li = document.createElement('li');
li.className = 'suggestion-item';
// Use state or country name if state is not available
const locationDetails = city.state ? `${city.state}, ${city.country}` : city.country;
li.innerHTML = `
<span class="material-symbols-rounded">location_on</span>
<span class="city-name-suggestion">${city.name}</span>
<span class="country-code">${locationDetails}</span>
`;
li.addEventListener('click', () => {
cityInput.value = city.name;
suggestionsList.classList.add('hidden');
getWeatherData(city.name);
});
suggestionsList.appendChild(li);
});
suggestionsList.classList.remove('hidden');
}
function updateCurrentWeather(data) {
cityNameEl.textContent = `${data.name}, ${data.sys.country}`;
// Format Date
const now = new Date();
const options = { weekday: 'short', day: 'numeric', month: 'short' };
currentDateEl.textContent = now.toLocaleDateString('en-US', options);
// Weather Icon
const iconCode = data.weather[0].icon;
weatherIconEl.src = `https://openweathermap.org/img/wn/${iconCode}@4x.png`;
weatherIconEl.alt = data.weather[0].description;
temperatureEl.textContent = Math.round(data.main.temp);
weatherConditionEl.textContent = data.weather[0].description;
humidityEl.textContent = `${data.main.humidity}%`;
windSpeedEl.textContent = `${Math.round(data.wind.speed * 3.6)} km/h`; // Convert m/s to km/h
feelsLikeEl.textContent = `${Math.round(data.main.feels_like)}°C`;
pressureEl.textContent = `${data.main.pressure} hPa`;
}
function updateForecast(data) {
forecastContainer.innerHTML = '';
// Filter out 1 forecast per day (we take the one around noon 12:00:00)
const dailyData = data.list.filter(item => item.dt_txt.includes('12:00:00'));
// Fallback if data length is short: grab evenly spaced forecasts
const forecastList = dailyData.length >= 5 ? dailyData.slice(0, 5) : data.list.filter((_, index) => index % 8 === 0).slice(0, 5);
forecastList.forEach(item => {
const date = new Date(item.dt * 1000);
const dayName = date.toLocaleDateString('en-US', { weekday: 'short' });
const iconCode = item.weather[0].icon;
const temp = Math.round(item.main.temp);
const forecastCard = document.createElement('div');
forecastCard.className = 'forecast-item glass-card';
forecastCard.innerHTML = `
<p class="forecast-day">${dayName}</p>
<img class="forecast-icon" src="https://openweathermap.org/img/wn/${iconCode}@2x.png" alt="Forecast Icon">
<p class="forecast-temp">${temp}°C</p>
`;
forecastContainer.appendChild(forecastCard);
});
}
function updateDynamicBackground(weatherCondition) {
const body = document.body;
// Remove existing background classes
body.classList.remove('bg-clear', 'bg-clouds', 'bg-rain', 'bg-snow', 'bg-thunderstorm');
// Map conditions to classes
const condition = weatherCondition.toLowerCase();
if (condition.includes('clear')) {
body.classList.add('bg-clear');
} else if (condition.includes('cloud')) {
body.classList.add('bg-clouds');
} else if (condition.includes('rain') || condition.includes('drizzle')) {
body.classList.add('bg-rain');
} else if (condition.includes('snow')) {
body.classList.add('bg-snow');
} else if (condition.includes('thunderstorm') || condition.includes('storm')) {
body.classList.add('bg-thunderstorm');
}
}
// --- State Management ---
function showLoading() {
introState.classList.add('hidden');
errorState.classList.add('hidden');
weatherDashboard.classList.add('hidden');
loadingState.classList.remove('hidden');
}
function showError(message) {
introState.classList.add('hidden');
loadingState.classList.add('hidden');
weatherDashboard.classList.add('hidden');
errorState.classList.remove('hidden');
// Capitalize first letter of error message
errorMessage.textContent = message.charAt(0).toUpperCase() + message.slice(1);
}
function showDashboard() {
introState.classList.add('hidden');
loadingState.classList.add('hidden');
errorState.classList.add('hidden');
weatherDashboard.classList.remove('hidden');
}