document.addEventListener('DOMContentLoaded', function() { const weatherWidget = document.getElementById('weatherWidget'); const weatherCity = document.getElementById('weatherCity'); const weatherForm = document.getElementById('weatherForm'); const weatherDisplay = document.getElementById('weatherDisplay'); weatherForm.addEventListener('submit', function(e) { e.preventDefault(); const city = weatherCity.value.trim(); if (city) { fetchWeather(city); } }); async function fetchWeather(city) { try { weatherDisplay.innerHTML = '

Loading weather data...

'; // Using OpenWeatherMap API with a free tier (you would need to replace with your own API key in production) const apiKey = 'demo'; // Using demo mode for example purposes const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`); if (!response.ok) { throw new Error('City not found or API limit reached'); } const data = await response.json(); displayWeather(data); } catch (error) { weatherDisplay.innerHTML = `

Error: ${error.message}

`; } } function displayWeather(data) { // For demo purposes, we'll show a simplified version since the API key is demo weatherDisplay.innerHTML = `

${data.name}, ${data.sys.country}

${Math.round(data.main.temp)}°C ${data.weather[0].description}

Feels like: ${Math.round(data.main.feels_like)}°C

Humidity: ${data.main.humidity}%

Wind: ${data.wind.speed} m/s

`; } // Initialize with a default city fetchWeather('London'); });