Display current weather in a given city
by Jordan Sayner
HTML
<div id="weather">Loading weather...</div>
CSS
#weather {
font-family: sans-serif;
max-width: 300px;
padding: 1em;
background: #eef6fb;
border-radius: 10px;
box-shadow: 0 0 10px #ccc;
}
JavaScript
const API_KEY = 'YOUR_API_KEY_HERE';
const CITY = 'London'; // Change this to any city
async function fetchWeather(city) {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
);
if (!response.ok) throw new Error("Weather data not available");
return await response.json();
}
function displayWeather(data) {
const container = document.getElementById("weather");
const { name, main, weather } = data;
container.innerHTML = `
<h2>${name} Weather</h2>
<p><strong>${weather[0].main}</strong> – ${weather[0].description}</p>
<p>🌡 Temp: ${main.temp}°C</p>
<p>💧 Humidity: ${main.humidity}%</p>
`;
}
function showError(message) {
const container = document.getElementById("weather");
container.innerHTML = `<p style="color:red;">${message}</p>`;
}
fetchWeather(CITY)
.then(displayWeather)
.catch(err => showError(err.message));