🌤️ Build a Simple Weather App
This project uses JavaScript and the OpenWeatherMap API to fetch and display real-time weather data based on city input.
🔧 HTML Structure
<div id="weather-container">
<input type="text" id="city" placeholder="Enter city" />
<button id="getWeather">Get Weather</button>
<div id="weatherResult"></div>
</div>
📜 JavaScript Code
const apiKey = "YOUR_API_KEY"; // Replace with your OpenWeatherMap API key
document.getElementById("getWeather").addEventListener("click", () => {
const city = document.getElementById("city").value;
const result = document.getElementById("weatherResult");
if (!city) {
result.textContent = "Please enter a city name.";
return;
}
fetch(\`https://api.openweathermap.org/data/2.5/weather?q=\${city}&appid=\${apiKey}&units=metric\`)
.then(response => response.json())
.then(data => {
if (data.cod === 200) {
result.innerHTML = \`
<h3>\${data.name}, \${data.sys.country}</h3>
<p>🌡️ Temperature: \${data.main.temp}°C</p>
<p>☁️ Condition: \${data.weather[0].main}</p>
<p>💧 Humidity: \${data.main.humidity}%</p>
\`;
} else {
result.textContent = "City not found.";
}
})
.catch(err => {
console.error(err);
result.textContent = "Error fetching weather data.";
});
});
🎨 Optional Styling
<style>
#weather-container {
max-width: 400px;
margin: auto;
text-align: center;
}
input {
padding: 8px;
width: 70%;
}
button {
padding: 8px 12px;
margin-left: 5px;
}
#weatherResult {
margin-top: 15px;
font-size: 1.1rem;
}
</style>
⚠️ Note: You must sign up at OpenWeatherMap to get your API key and enable CORS access.
✅ Concepts Covered
- Using external APIs
- Fetching JSON data
- DOM manipulation
- Error handling and validation