-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
352 lines (300 loc) · 11.7 KB
/
script.js
File metadata and controls
352 lines (300 loc) · 11.7 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
// API Configuration
const API_KEY = 'bd5e378503939ddaee76f12ad7a97608';
const WEATHER_API = 'https://api.openweathermap.org/data/2.5/weather';
const FORECAST_API = 'https://api.openweathermap.org/data/2.5/forecast';
// Global state
let currentUnit = 'celsius';
let searchHistory = JSON.parse(localStorage.getItem('weatherHistory')) || [];
// DOM Elements
const cityInput = document.getElementById('cityInput');
const searchBtn = document.getElementById('searchBtn');
const locationBtn = document.getElementById('locationBtn');
const unitToggle = document.getElementById('unitToggle');
const weatherInfo = document.getElementById('weatherInfo');
const forecastContainer = document.getElementById('forecastContainer');
const searchHistory_el = document.getElementById('searchHistory');
// Weather data elements
const cityName = document.getElementById('cityName');
const temperature = document.getElementById('temperature');
const description = document.getElementById('description');
const weatherIcon = document.getElementById('weatherIcon');
const feelsLike = document.getElementById('feelsLike');
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('windSpeed');
const visibility = document.getElementById('visibility');
const pressure = document.getElementById('pressure');
const uvIndex = document.getElementById('uvIndex');
const forecastGrid = document.getElementById('forecastGrid');
// Event Listeners
searchBtn.addEventListener('click', () => searchWeather());
cityInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') searchWeather();
});
locationBtn.addEventListener('click', getUserLocation);
unitToggle.addEventListener('click', toggleUnit);
// Weather Icons mapping
const weatherIcons = {
'01d': 'fas fa-sun',
'01n': 'fas fa-moon',
'02d': 'fas fa-cloud-sun',
'02n': 'fas fa-cloud-moon',
'03d': 'fas fa-cloud',
'03n': 'fas fa-cloud',
'04d': 'fas fa-clouds',
'04n': 'fas fa-clouds',
'09d': 'fas fa-cloud-showers-heavy',
'09n': 'fas fa-cloud-showers-heavy',
'10d': 'fas fa-cloud-rain',
'10n': 'fas fa-cloud-rain',
'11d': 'fas fa-bolt',
'11n': 'fas fa-bolt',
'13d': 'fas fa-snowflake',
'13n': 'fas fa-snowflake',
'50d': 'fas fa-smog',
'50n': 'fas fa-smog'
};
// Main search function
async function searchWeather(city = null) {
const searchCity = city || cityInput.value.trim();
if (!searchCity) {
showAlert('Please enter a city name!', 'error');
return;
}
try {
showLoading(true);
// Get current weather
const weatherData = await fetchWeatherData(searchCity);
displayCurrentWeather(weatherData);
// Get forecast data
const forecastData = await fetchForecastData(searchCity);
displayForecast(forecastData);
// Add to search history
addToHistory(searchCity);
// Show weather info
weatherInfo.classList.add('show');
forecastContainer.classList.add('show');
} catch (error) {
showAlert(error.message, 'error');
console.error('Weather fetch error:', error);
} finally {
showLoading(false);
}
}
// Fetch weather data
async function fetchWeatherData(city) {
const units = currentUnit === 'celsius' ? 'metric' : 'imperial';
const response = await fetch(`${WEATHER_API}?q=${city}&appid=${API_KEY}&units=${units}`);
if (!response.ok) {
if (response.status === 404) {
throw new Error('City not found! Please check the spelling.');
}
throw new Error('Weather data unavailable. Please try again.');
}
return await response.json();
}
// Fetch forecast data
async function fetchForecastData(city) {
const units = currentUnit === 'celsius' ? 'metric' : 'imperial';
const response = await fetch(`${FORECAST_API}?q=${city}&appid=${API_KEY}&units=${units}`);
if (!response.ok) {
throw new Error('Forecast data unavailable.');
}
return await response.json();
}
// Display current weather
function displayCurrentWeather(data) {
const tempUnit = currentUnit === 'celsius' ? '°C' : '°F';
const speedUnit = currentUnit === 'celsius' ? 'm/s' : 'mph';
cityName.textContent = `${data.name}, ${data.sys.country}`;
temperature.textContent = `${Math.round(data.main.temp)}${tempUnit}`;
description.textContent = data.weather[0].description;
// Set weather icon
const iconCode = data.weather[0].icon;
weatherIcon.innerHTML = `<i class="${weatherIcons[iconCode] || 'fas fa-sun'}"></i>`;
// Update details
feelsLike.textContent = `${Math.round(data.main.feels_like)}${tempUnit}`;
humidity.textContent = `${data.main.humidity}%`;
windSpeed.textContent = `${data.wind.speed} ${speedUnit}`;
visibility.textContent = `${(data.visibility / 1000).toFixed(1)} km`;
pressure.textContent = `${data.main.pressure} hPa`;
uvIndex.textContent = 'N/A'; // UV index requires separate API call
}
// Display forecast
function displayForecast(data) {
forecastGrid.innerHTML = '';
// Get one forecast per day (every 8th item = 24 hours)
const dailyForecasts = data.list.filter((_, index) => index % 8 === 0).slice(0, 5);
dailyForecasts.forEach(forecast => {
const date = new Date(forecast.dt * 1000);
const dayName = date.toLocaleDateString('en-US', { weekday: 'short' });
const iconCode = forecast.weather[0].icon;
const tempUnit = currentUnit === 'celsius' ? '°C' : '°F';
const forecastItem = document.createElement('div');
forecastItem.className = 'forecast-item';
forecastItem.innerHTML = `
<div class="forecast-day">${dayName}</div>
<div class="forecast-icon">
<i class="${weatherIcons[iconCode] || 'fas fa-sun'}"></i>
</div>
<div class="forecast-desc">${forecast.weather[0].description}</div>
<div class="forecast-temps">
<span class="forecast-high">${Math.round(forecast.main.temp_max)}${tempUnit}</span>
<span class="forecast-low">${Math.round(forecast.main.temp_min)}${tempUnit}</span>
</div>
`;
forecastGrid.appendChild(forecastItem);
});
}
// Get user location
function getUserLocation() {
if (!navigator.geolocation) {
showAlert('Geolocation is not supported by this browser.', 'error');
return;
}
showLoading(true);
navigator.geolocation.getCurrentPosition(
async (position) => {
try {
const { latitude, longitude } = position.coords;
const units = currentUnit === 'celsius' ? 'metric' : 'imperial';
const response = await fetch(
`${WEATHER_API}?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=${units}`
);
if (!response.ok) throw new Error('Location weather unavailable');
const data = await response.json();
displayCurrentWeather(data);
// Get forecast for current location
const forecastResponse = await fetch(
`${FORECAST_API}?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=${units}`
);
if (forecastResponse.ok) {
const forecastData = await forecastResponse.json();
displayForecast(forecastData);
}
cityInput.value = data.name;
weatherInfo.classList.add('show');
forecastContainer.classList.add('show');
} catch (error) {
showAlert('Unable to get weather for your location.', 'error');
} finally {
showLoading(false);
}
},
(error) => {
showLoading(false);
showAlert('Location access denied. Please enter a city manually.', 'error');
}
);
}
// Toggle temperature unit
function toggleUnit() {
currentUnit = currentUnit === 'celsius' ? 'fahrenheit' : 'celsius';
unitToggle.textContent = currentUnit === 'celsius' ? '°C' : '°F';
// Re-search current city if weather is displayed
if (weatherInfo.classList.contains('show') && cityInput.value) {
searchWeather();
}
}
// Add to search history
function addToHistory(city) {
if (!searchHistory.includes(city)) {
searchHistory.unshift(city);
if (searchHistory.length > 5) {
searchHistory = searchHistory.slice(0, 5);
}
localStorage.setItem('weatherHistory', JSON.stringify(searchHistory));
updateHistoryDisplay();
}
}
// Update search history display
function updateHistoryDisplay() {
searchHistory_el.innerHTML = '';
searchHistory.forEach(city => {
const historyItem = document.createElement('span');
historyItem.className = 'history-item';
historyItem.textContent = city;
historyItem.addEventListener('click', () => {
cityInput.value = city;
searchWeather();
});
searchHistory_el.appendChild(historyItem);
});
}
// Show loading state
function showLoading(isLoading) {
if (isLoading) {
searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
searchBtn.disabled = true;
locationBtn.disabled = true;
} else {
searchBtn.innerHTML = '<i class="fas fa-search"></i>';
searchBtn.disabled = false;
locationBtn.disabled = false;
}
}
// Show alert messages
function showAlert(message, type = 'info') {
// Create alert element
const alert = document.createElement('div');
alert.className = `alert alert-${type}`;
alert.innerHTML = `
<i class="fas fa-${type === 'error' ? 'exclamation-triangle' : 'info-circle'}"></i>
${message}
`;
// Add styles
alert.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: ${type === 'error' ? '#e74c3c' : '#3498db'};
color: white;
padding: 1rem 1.5rem;
border-radius: 10px;
box-shadow: 0 10px 25px rgba(0,0,0,0.2);
z-index: 1000;
animation: slideInRight 0.3s ease-out;
`;
document.body.appendChild(alert);
// Remove after 4 seconds
setTimeout(() => {
alert.style.animation = 'slideOutRight 0.3s ease-out';
setTimeout(() => alert.remove(), 300);
}, 4000);
}
// Add CSS animations for alerts
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(100%);
opacity: 0;
}
}
`;
document.head.appendChild(style);
// Initialize app
window.addEventListener('load', () => {
updateHistoryDisplay();
// Load default city
if (searchHistory.length > 0) {
cityInput.value = searchHistory[0];
searchWeather();
} else {
cityInput.value = 'Tehran';
searchWeather();
}
});