Tutorials JavaScript Project: Weather App
Ch 73 / 78
Chapter 73 Intermediate 25 min read JavaScript

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.

What you'll learn
How to register and use the OpenWeatherMap API
Making HTTP requests with fetch()
Handling async/await with error handling (try/catch)
Parsing and displaying JSON API responses
Building responsive UI with dynamic DOM updates
Adding loading states, error messages, and UX polish

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.

What you'll build
A single-page weather app with city search, live data from a public API, and a polished card UI showing temperature, humidity, wind, and conditions.
Skills applied
Fetch API, async/await, try/catch, DOM manipulation, template literals, event listeners, and responsive CSS.
Estimated time
~25 minutes to build from scratch. Suitable for Intermediate learners who have completed the Async JS and DOM sections.
API required
Free OpenWeatherMap account. Sign up at openweathermap.org — free tier allows up to 1,000 calls/day, more than enough for learning.

Tools & Concepts Used

Here's every JavaScript concept you'll apply in this project — most you've already covered in earlier chapters:

Fetch API
Use the built-in fetch() function to call the OpenWeatherMap REST endpoint and receive a JSON response.
async / await
Write clean, readable asynchronous code without callback hell or chained .then() calls.
try / catch
Handle network failures and invalid city names gracefully — showing friendly error messages instead of crashing.
JSON Parsing
Understand the API response shape and extract temperature, humidity, wind speed, and icon codes from nested JSON objects.
DOM Manipulation
Dynamically update the weather card — text content, icon src, and CSS classes — based on data returned from the API.
Event Listeners
Trigger a search on button click and on pressing Enter in the input field for a smooth user experience.
Template Literals
Build HTML strings and API URLs dynamically using backtick template syntax for clean, readable code.
Loading State
Show a loading spinner while the request is in flight so users know the app is working.

Project Roadmap — Step by Step

We'll build this project in 6 clear phases. Each phase adds a new layer to the app:

1
Get your API Key
Register a free account at openweathermap.org, generate an API key, and understand the current weather endpoint URL structure.
2
Build the HTML Structure
Create a search bar, a weather card container, and placeholder elements for all the data fields we'll populate with JS.
3
Style with CSS
Add a gradient background, card design, and responsive layout so the app looks polished on all screen sizes.
4
Write the Fetch Function
Create an async function that takes a city name, builds the API URL, fetches data, and returns the parsed JSON object.
5
Render Data to the DOM
Map the JSON response fields to your HTML elements — display temperature, city name, humidity, wind speed, and the weather icon.
6
Add Error Handling & UX Polish
Handle invalid cities, network errors, loading state feedback, and Enter-key support so the app feels complete and professional.

Step 1 — Setting Up the OpenWeatherMap API

Before writing code, you need a free API key from OpenWeatherMap. Here's how to get one:

1
Create a free account
Go to openweathermap.org and register. No credit card needed. The free tier gives 1,000 API calls per day.
2
Find your API key
After login, go to My API Keys in your profile. Copy the default key or generate a new one. It looks like: a1b2c3d4e5f6... (32 hex characters).
3
Understand the API endpoint
The endpoint for current weather by city name is: https://api.openweathermap.org/data/2.5/weather?q={city}&appid={KEY}&units=metric. The units=metric param returns temperature in Celsius.
Important
Never commit your API key to a public repository like GitHub. For learning purposes it's fine in a local file, but in production always store keys in environment variables on your server.

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.

HTML — index.html
<!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>
Pro Tip
Each element that will display weather data gets a unique 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:

CSS — style.css
/* 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:

JavaScript — app.js (Complete)
// ── 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 fetchWeather(city)
Marked async so we can use await inside. Uses a template literal to insert the city name and API key into the URL string dynamically.
if (!response.ok)
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.
renderWeather(data)
Receives the full JSON response object and maps each property to an HTML element. data.weather[0] is an array, so we access index [0] for the primary condition.
try / catch / finally
The try block runs the happy path. catch displays the error message if anything goes wrong. finally hides the loader regardless of success or failure.
show() / hide() helpers
Small utility functions that add/remove the hidden CSS class. Keeps the UI control logic clean and avoids repetition.
keydown → Enter
Listening for the Enter key on the input gives users a natural keyboard experience without needing to click the button.
Advertisement

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:

JSON — Sample API Response (Vadodara)
{
  "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:

Dark/Light theme toggle
Recent search history
Geolocation auto-detect
5-day forecast
°C / °F unit toggle
Favourite cities list
localStorage caching
Animated weather backgrounds
Challenge
Add a geolocation feature: use 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:

Live Editor
✎ Editor
👁 Preview
Note
The live editor above uses mock data (no real API key needed). Try searching: Mumbai, Delhi, Vadodara, London, Tokyo, or Paris.
Advertisement
Quick Check — Chapter 73

In the Weather App, why must we manually check response.ok instead of just using fetch() alone?

Chapter Summary
  • You built a complete Weather App using Fetch API, async/await, and DOM manipulation.
  • fetch() doesn't throw on 404 — always check response.ok and throw manually for bad status codes.
  • The try / catch / finally pattern 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel