-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
344 lines (293 loc) · 10.9 KB
/
script.js
File metadata and controls
344 lines (293 loc) · 10.9 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
// Weather API configuration
const API_KEY = 'f9bd2dd3df2b4869b3822631252708';
const BASE_URL = 'https://api.weatherapi.com/v1';
// DOM elements
const weatherForm = document.getElementById('weatherForm');
const locationInput = document.getElementById('locationInput');
const searchBtn = document.getElementById('searchBtn');
const refreshBtn = document.getElementById('refreshBtn');
const loading = document.getElementById('loading');
const errorMessage = document.getElementById('errorMessage');
const errorText = document.getElementById('errorText');
const weatherData = document.getElementById('weatherData');
const themeToggle = document.getElementById('themeToggle');
const themeIcon = document.getElementById('themeIcon');
// Weather data elements
const locationName = document.getElementById('locationName');
const localTime = document.getElementById('localTime');
const temperature = document.getElementById('temperature');
const condition = document.getElementById('condition');
const feelsLike = document.getElementById('feelsLike');
const weatherIcon = document.getElementById('weatherIcon');
const visibility = document.getElementById('visibility');
const humidity = document.getElementById('humidity');
const wind = document.getElementById('wind');
const pressure = document.getElementById('pressure');
const uv = document.getElementById('uv');
const precipitation = document.getElementById('precipitation');
const cloud = document.getElementById('cloud');
const windDir = document.getElementById('windDir');
// Store current location for refresh functionality
let currentLocation = '';
// Event listeners
weatherForm.addEventListener('submit', handleFormSubmit);
refreshBtn.addEventListener('click', handleRefresh);
themeToggle.addEventListener('click', toggleTheme);
// Dark mode functionality
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
// Update icon
if (newTheme === 'dark') {
themeIcon.className = 'fas fa-sun';
themeToggle.title = 'Switch to light mode';
} else {
themeIcon.className = 'fas fa-moon';
themeToggle.title = 'Switch to dark mode';
}
}
// Initialize theme
function initializeTheme() {
const savedTheme = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = savedTheme || (prefersDark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
if (theme === 'dark') {
themeIcon.className = 'fas fa-sun';
themeToggle.title = 'Switch to light mode';
} else {
themeIcon.className = 'fas fa-moon';
themeToggle.title = 'Switch to dark mode';
}
}
// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem('theme')) {
const theme = e.matches ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', theme);
if (theme === 'dark') {
themeIcon.className = 'fas fa-sun';
themeToggle.title = 'Switch to light mode';
} else {
themeIcon.className = 'fas fa-moon';
themeToggle.title = 'Switch to dark mode';
}
}
});
// Handle form submission
async function handleFormSubmit(e) {
e.preventDefault();
const location = locationInput.value.trim();
if (!location) {
showError('Please enter a location');
return;
}
await fetchWeatherData(location);
}
// Handle refresh button click
async function handleRefresh() {
if (currentLocation) {
await fetchWeatherData(currentLocation);
}
}
// Fetch weather data from API
async function fetchWeatherData(location) {
try {
showLoading();
hideError();
hideWeatherData();
const response = await fetch(`${BASE_URL}/current.json?key=${API_KEY}&q=${encodeURIComponent(location)}&aqi=yes`);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || 'Failed to fetch weather data');
}
const data = await response.json();
displayWeatherData(data);
currentLocation = location;
} catch (error) {
console.error('Error fetching weather data:', error);
showError(error.message);
} finally {
hideLoading();
}
}
// Display weather data
function displayWeatherData(data) {
const { location, current } = data;
// Location and time
locationName.textContent = `${location.name}, ${location.region}, ${location.country}`;
localTime.textContent = `Local time: ${formatDateTime(location.localtime)}`;
// Main weather info
temperature.textContent = Math.round(current.temp_c);
condition.textContent = current.condition.text;
feelsLike.textContent = Math.round(current.feelslike_c);
weatherIcon.src = `https:${current.condition.icon}`;
weatherIcon.alt = current.condition.text;
// Weather details
visibility.textContent = `${current.vis_km} km`;
humidity.textContent = `${current.humidity}%`;
wind.textContent = `${current.wind_kph} km/h`;
pressure.textContent = `${current.pressure_mb} mb`;
uv.textContent = getUVIndexText(current.uv);
precipitation.textContent = `${current.precip_mm} mm`;
cloud.textContent = `${current.cloud}%`;
windDir.textContent = current.wind_dir;
// Show weather data with animation
weatherData.classList.remove('d-none');
weatherData.classList.add('fade-in');
// Update input value to show what was searched
locationInput.value = location.name;
}
// Format date and time
function formatDateTime(dateTimeString) {
const date = new Date(dateTimeString);
return date.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
// Get UV index description
function getUVIndexText(uvIndex) {
if (uvIndex <= 2) return `${uvIndex} (Low)`;
if (uvIndex <= 5) return `${uvIndex} (Moderate)`;
if (uvIndex <= 7) return `${uvIndex} (High)`;
if (uvIndex <= 10) return `${uvIndex} (Very High)`;
return `${uvIndex} (Extreme)`;
}
// Show loading state
function showLoading() {
loading.classList.remove('d-none');
searchBtn.disabled = true;
searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
}
// Hide loading state
function hideLoading() {
loading.classList.add('d-none');
searchBtn.disabled = false;
searchBtn.innerHTML = '<i class="fas fa-search"></i>';
}
// Show error message
function showError(message) {
errorText.textContent = message;
errorMessage.classList.remove('d-none');
// Auto-hide error after 5 seconds
setTimeout(() => {
hideError();
}, 5000);
}
// Hide error message
function hideError() {
errorMessage.classList.add('d-none');
}
// Hide weather data
function hideWeatherData() {
weatherData.classList.add('d-none');
weatherData.classList.remove('fade-in');
}
// Get user's location and fetch weather data
async function getUserLocation() {
if ('geolocation' in navigator) {
try {
showLoading();
const position = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 60000
});
});
const { latitude, longitude } = position.coords;
const location = `${latitude},${longitude}`;
await fetchWeatherData(location);
} catch (error) {
console.error('Error getting user location:', error);
showError('Unable to get your location. Please enter a location manually.');
}
} else {
showError('Geolocation is not supported by this browser.');
}
}
// Add keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Press Ctrl/Cmd + Enter to search
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
weatherForm.dispatchEvent(new Event('submit'));
}
// Press F5 to refresh (if weather data is shown)
if (e.key === 'F5' && !weatherData.classList.contains('d-none')) {
e.preventDefault();
handleRefresh();
}
});
// Auto-focus on input when page loads
window.addEventListener('load', () => {
// Initialize theme first
initializeTheme();
locationInput.focus();
// Add placeholder suggestions
const suggestions = [
'New York',
'London',
'Tokyo',
'Paris',
'Sydney',
'Mumbai',
'Dubai',
'Los Angeles'
];
let currentSuggestion = 0;
const rotatePlaceholder = () => {
locationInput.placeholder = `Try "${suggestions[currentSuggestion]}"...`;
currentSuggestion = (currentSuggestion + 1) % suggestions.length;
};
// Rotate placeholder every 3 seconds when input is empty
setInterval(() => {
if (!locationInput.value && document.activeElement !== locationInput) {
rotatePlaceholder();
}
}, 3000);
});
// Add a button to get user's current location
function addLocationButton() {
const locationBtn = document.createElement('button');
locationBtn.type = 'button';
locationBtn.className = 'btn btn-outline-secondary';
locationBtn.innerHTML = '<i class="fas fa-location-arrow"></i>';
locationBtn.title = 'Use my current location';
locationBtn.onclick = getUserLocation;
const searchContainer = document.querySelector('.search-container .d-flex');
searchContainer.insertBefore(locationBtn, searchBtn);
}
// Initialize location button
addLocationButton();
// Handle online/offline status
window.addEventListener('online', () => {
if (errorMessage.textContent.includes('offline') || errorMessage.textContent.includes('network')) {
hideError();
}
});
window.addEventListener('offline', () => {
showError('You are offline. Please check your internet connection.');
});
// Error handling for fetch requests
function handleFetchError(error) {
if (error.name === 'TypeError' && error.message.includes('fetch')) {
return 'Network error. Please check your internet connection.';
}
if (error.message.includes('404')) {
return 'Location not found. Please check the spelling and try again.';
}
if (error.message.includes('401')) {
return 'API key error. Please contact the administrator.';
}
if (error.message.includes('403')) {
return 'Access denied. API key may have exceeded its quota.';
}
return error.message || 'An unexpected error occurred.';
}