-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
219 lines (185 loc) · 8.33 KB
/
script.js
File metadata and controls
219 lines (185 loc) · 8.33 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
/**
* ============================================
* 🌤️ Modern Weather App - JavaScript
* ============================================
* Built with vanilla JS using async/await
* API: OpenWeatherMap (https://openweathermap.org)
*/
// ─── Configuration ──────────────────────────────────────
// ⚠️ In production, NEVER expose your API key in client-side code.
// Use a backend proxy server to keep it secure.
const API_KEY = 'fb53c40438091c02b81af75adb45c6be';
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';
// ─── DOM Elements ───────────────────────────────────────
// Using getElementById for faster and cleaner DOM access
const searchInput = document.getElementById('cityInput');
const searchBtn = document.getElementById('searchBtn');
// UI State Elements
const initialState = document.getElementById('initialState');
const loadingState = document.getElementById('loadingState');
const errorState = document.getElementById('errorState');
const weatherInfo = document.getElementById('weatherInfo');
// Weather Display Elements
const domTemp = document.getElementById('temperature');
const domCity = document.getElementById('cityName');
const domCondition = document.getElementById('weatherCondition');
const domIcon = document.getElementById('weatherIcon');
// Weather Detail Elements
const domFeelsLike = document.getElementById('feelsLike');
const domHumidity = document.getElementById('humidity');
const domWindSpeed = document.getElementById('windSpeed');
const domVisibility = document.getElementById('visibility');
// New Weather Detail Elements
const domTempMax = document.getElementById('tempMax');
const domTempMin = document.getElementById('tempMin');
const domSunrise = document.getElementById('sunriseTime');
const domSunset = document.getElementById('sunsetTime');
const domPressure = document.getElementById('pressure');
const domCloudCover = document.getElementById('cloudCover');
const domWindGust = document.getElementById('windGust');
// ─── Utility: Capitalize First Letter of Each Word ──────
function capitalizeWords(str) {
return str
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
// ─── Utility: Convert Unix Timestamp to Local Time ──────
function formatTime(unixTimestamp, timezoneOffset) {
// Create date from unix timestamp (API gives seconds, JS needs milliseconds)
const date = new Date((unixTimestamp + timezoneOffset) * 1000);
// Get UTC hours and minutes (since we already applied the offset)
let hours = date.getUTCHours();
let minutes = date.getUTCMinutes();
// Format to 12-hour clock
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // 0 should be 12
minutes = minutes < 10 ? '0' + minutes : minutes;
return `${hours}:${minutes} ${ampm}`;
}
// ─── Utility: Manage UI States ──────────────────────────
// Controls which section is visible: initial, loading, error, or success
function updateUIState(state) {
// Hide everything first
initialState.classList.add('hidden');
loadingState.classList.add('hidden');
errorState.classList.add('hidden');
weatherInfo.classList.add('hidden');
// Show the requested state
switch (state) {
case 'initial':
initialState.classList.remove('hidden');
break;
case 'loading':
loadingState.classList.remove('hidden');
break;
case 'error':
errorState.classList.remove('hidden');
break;
case 'success':
weatherInfo.classList.remove('hidden');
break;
}
}
// ─── Utility: Update Error Message Dynamically ──────────
function showError(message) {
const errorText = errorState.querySelector('p');
if (errorText) {
errorText.textContent = message;
}
updateUIState('error');
}
// ─── Core: Fetch & Display Weather Data ─────────────────
/**
* Fetches weather data from OpenWeatherMap API and paints the UI.
*
* Uses async/await for clean, readable asynchronous code.
* The try/catch block handles network errors, invalid cities,
* and API issues gracefully.
*
* @param {string} city - The city name entered by the user
*/
async function fetchAndPaintWeather(city) {
// 1. Show loading state immediately
updateUIState('loading');
try {
// 2. Make the API call
// units=metric returns temperature in Celsius directly
const response = await fetch(
`${BASE_URL}?q=${encodeURIComponent(city)}&appid=${API_KEY}&units=metric`
);
// 3. Handle HTTP errors
// fetch() only rejects on network failures, NOT on HTTP errors like 404
if (response.status === 401) {
throw new Error('API key is invalid or not yet activated. Please check your key.');
} else if (response.status === 404) {
throw new Error('City not found. Please check the spelling and try again.');
} else if (!response.ok) {
throw new Error('Something went wrong. Please try again later.');
}
// 4. Parse the JSON response
const data = await response.json();
// 5. Paint the main weather data
domTemp.textContent = `${Math.round(data.main.temp)}°C`;
domCity.textContent = `${data.name}, ${data.sys.country}`;
domCondition.textContent = capitalizeWords(data.weather[0].description);
// 6. Set the weather icon (using 4x size for crisp display)
const iconCode = data.weather[0].icon;
domIcon.src = `https://openweathermap.org/img/wn/${iconCode}@4x.png`;
domIcon.alt = data.weather[0].description;
// 7. Paint the weather details
domFeelsLike.textContent = `${Math.round(data.main.feels_like)}°C`;
domHumidity.textContent = `${data.main.humidity}%`;
domWindSpeed.textContent = `${Math.round(data.wind.speed * 3.6)} km/h`;
// API returns visibility in meters, convert to km
domVisibility.textContent = `${(data.visibility / 1000).toFixed(1)} km`;
// 8. Paint new sections
// Min/Max Temperature
domTempMax.textContent = `${Math.round(data.main.temp_max)}°`;
domTempMin.textContent = `${Math.round(data.main.temp_min)}°`;
// Sunrise & Sunset (convert unix timestamps to readable time)
domSunrise.textContent = formatTime(data.sys.sunrise, data.timezone);
domSunset.textContent = formatTime(data.sys.sunset, data.timezone);
// Extra Details
domPressure.textContent = `${data.main.pressure} hPa`;
domCloudCover.textContent = `${data.clouds.all}%`;
domWindGust.textContent = data.wind.gust
? `${Math.round(data.wind.gust * 3.6)} km/h`
: 'N/A';
// 8. Show the weather data
updateUIState('success');
} catch (error) {
// 9. Handle any errors gracefully
console.error('🌧️ Weather Fetch Error:', error.message);
showError(error.message);
}
}
// ─── Event Handler: Trigger Search ──────────────────────
function triggerSearch() {
const city = searchInput.value.trim();
if (city === '') {
// Shake the input to indicate it's empty
searchInput.classList.add('shake');
searchInput.focus();
// Remove shake animation after it completes
setTimeout(() => {
searchInput.classList.remove('shake');
}, 500);
return;
}
fetchAndPaintWeather(city);
}
// ─── Event Listeners ────────────────────────────────────
// Click the search button
searchBtn.addEventListener('click', triggerSearch);
// Press Enter in the input field
searchInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
triggerSearch();
}
});
// Focus the input field when the page loads for instant typing
window.addEventListener('load', () => {
searchInput.focus();
});