Project: Build a Weather App with JavaScript
Bring together Fetch API, async/await, DOM manipulation, and real-world API integration by building a fully functional Weather App that shows live weather data for any city in the world.
fetch()Project Overview
In this project you'll build a Weather App that lets users search any city and instantly display real-time weather data — temperature, humidity, wind speed, weather condition, and a matching weather icon — fetched from the OpenWeatherMap API.
This project ties together many of the core JS skills you've learned so far: the Fetch API, async/await, DOM manipulation, event listeners, and error handling — all inside a clean, styled UI.
Tools & Concepts Used
Here's every JavaScript concept you'll apply in this project — most you've already covered in earlier chapters:
fetch()
function to call the OpenWeatherMap REST endpoint and receive a JSON response..then() calls.Project Roadmap — Step by Step
We'll build this project in 6 clear phases. Each phase adds a new layer to the app:
async function
that takes a city name, builds the API URL, fetches data, and returns the parsed
JSON
object.Step 1 — Setting Up the OpenWeatherMap API
Before writing code, you need a free API key from OpenWeatherMap. Here's how to get one:
a1b2c3d4e5f6... (32 hex characters).
https://api.openweathermap.org/data/2.5/weather?q={city}&appid={KEY}&units=metric.
The units=metric param returns temperature in
Celsius.
Step 2 — HTML Structure
Keep the HTML minimal — just the structure you'll populate with JavaScript. The card is hidden initially and shown only when data loads successfully.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weather App</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="app">
<h1 class="app-title">⛅ Weather App</h1>
<!-- Search Bar -->
<div class="search-bar">
<input
type="text"
id="cityInput"
placeholder="Enter city name…"
autocomplete="off"
/>
<button id="searchBtn">Search</button>
</div>
<!-- Loading Spinner -->
<div class="loader hidden" id="loader">Loading…</div>
<!-- Error Message -->
<div class="error-msg hidden" id="errorMsg"></div>
<!-- Weather Card -->
<div class="weather-card hidden" id="weatherCard">
<img id="weatherIcon" src="" alt="weather icon" />
<h2 id="cityName"></h2>
<p id="description"></p>
<div class="temp" id="temperature"></div>
<div class="details">
<span id="humidity"></span>
<span id="windSpeed"></span>
<span id="feelsLike"></span>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
id. This makes it trivial to select and update them with
document.getElementById() in your JavaScript.
Step 3 — Styling the App (CSS)
Here's a clean, complete CSS for a glass-morphism weather card with a gradient sky background:
/* Reset & base */
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #1e3a5f 0%, #2d6a9f 50%, #0d2137 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
/* App wrapper */
.app {
width: 100%;
max-width: 420px;
text-align: center;
}
.app-title {
color: #fff;
font-size: 28px;
font-weight: 700;
margin-bottom: 24px;
letter-spacing: -0.5px;
}
/* Search bar */
.search-bar {
display: flex;
gap: 8px;
margin-bottom: 20px;
}
.search-bar input {
flex: 1;
padding: 12px 16px;
border: none;
border-radius: 12px;
background: rgba(255, 255, 255, 0.15);
color: #fff;
font-size: 15px;
outline: none;
backdrop-filter: blur(8px);
transition: background 0.2s;
}
.search-bar input::placeholder { color: rgba(255,255,255,0.55); }
.search-bar input:focus { background: rgba(255,255,255,0.22); }
.search-bar button {
padding: 12px 20px;
border: none;
border-radius: 12px;
background: #f7df1e;
color: #1a1a14;
font-size: 14px;
font-weight: 700;
cursor: pointer;
transition: transform 0.15s, filter 0.15s;
}
.search-bar button:hover { filter: brightness(1.1); transform: scale(1.03); }
/* Loader */
.loader {
color: rgba(255,255,255,0.8);
font-size: 15px;
padding: 20px;
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }
/* Error */
.error-msg {
background: rgba(239, 68, 68, 0.2);
border: 1px solid rgba(239, 68, 68, 0.4);
border-radius: 12px;
color: #fca5a5;
padding: 14px 18px;
font-size: 14px;
}
/* Weather Card */
.weather-card {
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(14px);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 20px;
padding: 32px 24px;
color: #fff;
animation: fadeIn 0.4s ease;
}
@keyframes fadeIn { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }
.weather-card img { width: 80px; height: 80px; margin: 0 auto 8px; display: block; }
.weather-card h2 { font-size: 26px; font-weight: 700; margin-bottom: 4px; }
.weather-card p { color: rgba(255,255,255,0.7); text-transform: capitalize; margin-bottom: 16px; }
.temp { font-size: 64px; font-weight: 800; line-height: 1; margin-bottom: 20px; }
.temp::after { content: '°C'; font-size: 28px; font-weight: 400; vertical-align: top; margin-top: 12px; display: inline-block; }
.details { display: flex; justify-content: space-around; gap: 12px; }
.details span {
background: rgba(255,255,255,0.1);
border-radius: 10px;
padding: 10px 14px;
font-size: 13px;
line-height: 1.5;
flex: 1;
}
/* Utility */
.hidden { display: none; }
Step 4 & 5 — JavaScript Logic
This is the heart of the project. Here's the complete, commented app.js file. We'll break it down after the code:
// ── CONFIG ─────────────────────────────────────────────────
const API_KEY = "YOUR_API_KEY_HERE"; // Replace with your OpenWeatherMap key
const BASE_URL = "https://api.openweathermap.org/data/2.5/weather";
// ── DOM REFERENCES ─────────────────────────────────────────
const cityInput = document.getElementById("cityInput");
const searchBtn = document.getElementById("searchBtn");
const loader = document.getElementById("loader");
const errorMsg = document.getElementById("errorMsg");
const weatherCard = document.getElementById("weatherCard");
// ── FETCH WEATHER DATA ──────────────────────────────────────
async function fetchWeather(city) {
const url = `${BASE_URL}?q=${city}&appid=${API_KEY}&units=metric`;
const response = await fetch(url);
// 404 = city not found; throw to be caught below
if (!response.ok) {
throw new Error(`City not found: "${city}"`);
}
return response.json(); // parse & return JSON
}
// ── UPDATE THE DOM ──────────────────────────────────────────
function renderWeather(data) {
const iconCode = data.weather[0].icon;
document.getElementById("weatherIcon").src =
`https://openweathermap.org/img/wn/${iconCode}@2x.png`;
document.getElementById("cityName").textContent =
`${data.name}, ${data.sys.country}`;
document.getElementById("description").textContent =
data.weather[0].description;
document.getElementById("temperature").textContent =
Math.round(data.main.temp);
document.getElementById("humidity").innerHTML =
`💧 Humidity<br>${data.main.humidity}%`;
document.getElementById("windSpeed").innerHTML =
`💨 Wind<br>${data.wind.speed} m/s`;
document.getElementById("feelsLike").innerHTML =
`🌡 Feels like<br>${Math.round(data.main.feels_like)}°C`;
}
// ── SHOW / HIDE HELPERS ─────────────────────────────────────
function show(el) { el.classList.remove("hidden"); }
function hide(el) { el.classList.add("hidden"); }
// ── MAIN SEARCH HANDLER ─────────────────────────────────────
async function handleSearch() {
const city = cityInput.value.trim();
if (!city) return; // do nothing if input is empty
// Reset UI state
hide(weatherCard); hide(errorMsg);
show(loader);
try {
const data = await fetchWeather(city);
renderWeather(data);
show(weatherCard);
} catch (err) {
errorMsg.textContent = err.message;
show(errorMsg);
} finally {
hide(loader); // always hide loader when done
}
}
// ── EVENT LISTENERS ─────────────────────────────────────────
searchBtn.addEventListener("click", handleSearch);
// Also search on Enter key press
cityInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") handleSearch();
});
Code Walkthrough
Let's break down the key parts of app.js
so you understand every decision:
async so we can use
await inside. Uses a template literal to insert the
city name and API key into the URL string dynamically.
fetch() only rejects on
network failure — it won't throw for a 404. We must manually check response.ok and throw an error for bad HTTP status
codes.data.weather[0] is an array, so
we access index [0] for the primary condition.try block runs the
happy path. catch displays the error message if
anything goes wrong. finally hides the loader
regardless of success or failure.hidden CSS class. Keeps the UI control logic clean
and avoids repetition.Enter key
on the input gives users a natural keyboard experience without needing to click the
button.Understanding the API Response
Here's what the OpenWeatherMap JSON response looks like for a city search — only the fields we use are shown here:
{
"name": "Vadodara",
"sys": {
"country": "IN"
},
"weather": [
{
"description": "scattered clouds",
"icon": "03d" // used to build icon URL
}
],
"main": {
"temp": 36.4, // Current temperature in °C
"feels_like": 38.2, // Perceived temperature
"humidity": 42 // Relative humidity %
},
"wind": {
"speed": 3.6 // Wind speed in m/s
}
}
| JSON Property | What It Contains | How We Use It |
|---|---|---|
data.name |
City name string | Display in #cityName |
data.sys.country |
2-letter country code | Append to city name: "Vadodara, IN" |
data.weather[0].icon |
Icon code string (e.g. "03d") | Build icon image URL for OpenWeatherMap CDN |
data.weather[0].description |
Condition text: "scattered clouds" | Display in #description |
data.main.temp |
Temperature (°C with units=metric) |
Round and display in #temperature |
data.main.humidity |
Humidity percentage | Display in #humidity |
data.wind.speed |
Wind speed in m/s | Display in #windSpeed |
Step 6 — Extend the Project
Once the basic version works, try adding these features to level up your skills. Each one practices a different JavaScript concept:
navigator.geolocation.getCurrentPosition() to get the user's
coordinates, then pass them to the OpenWeatherMap lat&lon
endpoint instead of a city name.
Try It Yourself — Live Preview
Below is a mock weather app (no API key required) to show the complete UI. Explore the code and preview in the editor below:
Mumbai, Delhi, Vadodara, London, Tokyo, or Paris.
In the Weather App, why must we manually check response.ok instead of just using fetch() alone?
- You built a complete Weather App using Fetch API, async/await, and DOM manipulation.
fetch()doesn't throw on 404 — always checkresponse.okand throw manually for bad status codes.- The
try / catch / finallypattern gives you clean separation of success logic, error handling, and cleanup. - Template literals make building API URLs and HTML strings clean and readable.
- Small helper functions like
show()/hide()keep your code DRY and maintainable. - API keys should never be committed to public repositories — use server-side environment variables in production.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.