11const cityInput = document . getElementById ( 'city-input' ) ;
2- const weatherData = document . getElementById ( 'weather-data' ) ;
2+ const weatherData = document . getElementById ( 'weather-data' ) ; // You aren't using this yet, but kept it in
33const cityName = document . getElementById ( 'city-name' ) ;
4- const temperature = document . getElementById ( 'temperature' ) ;
4+ const temperatureElement = document . getElementById ( 'temperature' ) ;
55const weatherDesc = document . getElementById ( 'weather-description' ) ;
66const humidityValue = document . getElementById ( 'humidity' ) ;
77const windspeedValue = document . getElementById ( 'windspeed' ) ;
8- const search = document . querySelector ( '# weather-form button ') ;
8+ const form = document . getElementById ( ' weather-form') ; // Target the form, not just the button
99
10- search . addEventListener ( 'click' , ( ) => {
11- const APIKey = 'f23d9832cb86b7e516bf0bc3272bf1de' ;
12- const city = cityInput . value ;
13- if ( city == '' ) {
10+ const API_KEY = 'f23d9832cb86b7e516bf0bc3272bf1de' ; // Keep key separate
11+
12+ // Use the 'submit' event on the form, not 'click' on the button.
13+ // This handles both clicking the button and pressing "Enter".
14+ form . addEventListener ( 'submit' , ( event ) => {
15+ event . preventDefault ( ) ; // STOPS the page reload
16+
17+ const city = cityInput . value . trim ( ) ;
18+
19+ // If city is empty, stop.
20+ if ( ! city ) {
1421 return ;
1522 }
16- fetch ( `https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={f23d9832cb86b7e516bf0bc3272bf1de}` )
17- } )
23+
24+ fetchWeather ( city ) ;
25+ } ) ;
26+
27+ function fetchWeather ( city ) {
28+ // Correct URL structure: uses 'q' for city, adds units=metric, and uses ${} for variables
29+ const url = `https://api.openweathermap.org/data/2.5/weather?q=${ city } &units=metric&appid=${ API_KEY } ` ;
30+
31+ fetch ( url )
32+ . then ( response => {
33+ if ( ! response . ok ) {
34+ throw new Error ( 'City not found' ) ;
35+ }
36+ return response . json ( ) ;
37+ } )
38+ . then ( data => {
39+ // Update UI
40+ cityName . textContent = data . name ;
41+ temperatureElement . textContent = `${ Math . round ( data . main . temp ) } °C` ; // Added missing ${} and unit
42+ weatherDesc . textContent = data . weather [ 0 ] . description ;
43+ humidityValue . textContent = `${ data . main . humidity } %` ;
44+ windspeedValue . textContent = `${ data . wind . speed } km/h` ;
45+ } )
46+ . catch ( error => {
47+ console . error ( 'Error fetching weather data:' , error ) ;
48+ alert ( "City not found or API error." ) ;
49+ } ) ;
50+ }
0 commit comments