Skip to content

Weather Lookup

Medium ~25 min

What you'll build

A page with a city search input. Typing a city name and clicking Search fetches weather data from a free API and displays temperature and conditions.

Goals

  • Use fetch with async/await to get weather data
  • Parse JSON responses and extract relevant fields
  • Handle errors (city not found, network failure)
  • Update the DOM with weather information

Prerequisites

  • async/await and Promises
  • fetch API basics
  • DOM selection and event listeners

Steps

  1. 1

    Create the HTML

    Create a search input, a search button, and a result div. The result div will show the weather information.

    Code
    <input id="city" placeholder="Enter city name">
    <button id="search">Search</button>
    <div id="result">Weather will appear here</div>

    Expected result

    A search input, button, and result area appear.

  2. 2

    Write the fetch function

    Write an async function that fetches weather data from a free API (e.g., Open-Meteo). Use try/catch for error handling.

    Code
    async function getWeather(city) {
      const url = `https://geocoding-api.open-meteo.com/v1/search?name=${city}&count=1`;
      const geoRes = await fetch(url);
      const geo = await geoRes.json();
      if (!geo.results || !geo.results[0]) throw new Error("City not found");
      const { latitude, longitude } = geo.results[0];
      const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m`;
      const wRes = await fetch(weatherUrl);
      const w = await wRes.json();
      return w.current.temperature_2m;
    }

    Expected result

    Calling getWeather('London') returns the current temperature.

  3. 3

    Wire the search button

    Add a click listener that reads the city input, calls getWeather, and updates the result div. Handle errors gracefully.

    Code
    const resultEl = document.getElementById("result");
    document.getElementById("search").addEventListener("click", async () => {
      const city = document.getElementById("city").value.trim();
      if (!city) return;
      resultEl.textContent = "Loading...";
      try {
        const temp = await getWeather(city);
        resultEl.textContent = `Temperature in ${city}: ${temp}°C`;
      } catch (err) {
        resultEl.textContent = `Error: ${err.message}`;
      }
    });

    Expected result

    Searching for a city shows its current temperature, or an error message if not found.

  4. 4

    Add input validation & error handling

    Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.

    Code
    function safeParse(value) {
      if (value === null || value === undefined || value === "") {
        throw new Error("Input is empty");
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        throw new Error(`"${value}" is not a valid number`);
      }
      return num;
    }
    
    try {
      const n = safeParse(userInput);
      process(n);
    } catch (err) {
      console.error(err.message);
    }

    Expected result

    Empty or non-number input shows an error message instead of crashing; valid numbers process normally.

  5. 5

    Add event listeners & interaction

    Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.

    Code
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    Expected result

    Clicking the button or pressing Enter triggers the main logic; empty input is ignored.

Try it yourself

What you learned

You used async/await with fetch to retrieve real data from an API, parsed JSON responses, and handled errors with try/catch — the standard pattern for any web app that talks to a server.

Related Resources

Related Lessons

Related Practice

Related Cheatsheets

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic