🧩 Class Activity: Building the JavaScript Logic for a
Weather App
🎯 Objective
Students will understand how to:
● Use the Fetch API to get data from an external weather API.
● Handle user input events.
● Update and display results dynamically on a webpage using DOM manipulation.
🧠 Concepts Covered
● JavaScript functions
● Event listeners (keypress)
● API integration with fetch()
● Working with JSON data
● Updating webpage content dynamically
🪜 Activity Steps
Step 1: Setup
1. Provided the HTML file that includes:
○ A text box (.search-box) to enter city names.
○ Elements with classes like .city, .date, .temp, .weather, .hi-low for
displaying results.
2. The provided JavaScript file ([Link]) or ask them to recreate it step by step.
Step 2: Understanding the API Connection
Discuss the following code:
const api = {
key: "your_api_key",
base: "[Link]
};
●
👉
● Ask students:
What does the key represent?
👉 What will happen if we change the base URL?
Step 3: Handling User Input
Explain:
const searchbox = [Link]('.search-box');
[Link]('keypress', setQuery);
● Complete the following tasks:
○ Log the keypress event in the console.
○ Identify what key code represents the Enter key.
Step 4: Fetching Weather Data
Analyze:
fetch(`${[Link]}weather?q=${query}&units=metric&APPID=${[Link]}`)
● Complete the following tasks:
Answer the following questions:
○ What happens if the city name is invalid?
○ How could we show an error message to the user?
🧩 Mini-task:
Modify the code to display an alert if the city name is not found.
Step 5: Displaying Results
Discuss:
let city = [Link]('.location .city');
[Link] = `${[Link]}, ${[Link]}`;
● Students are required to:
○ Add one more line to display humidity and wind speed using data from
[Link] and [Link].
Step 6: Date Builder Function
Understand:
function dateBuilder(d) {
let day = days[[Link]()];
let date = [Link]();
...
}
● Challenge students to modify it to display time (HH:MM format) along with the date.
🧩 Step 7: Reflection
After completing the app:
● Discuss how asynchronous code (fetch, .then()) works.
● Students are required to :
○ How would this code change if we used async/await instead?
✅ Expected Output
● The user enters a city name → presses Enter → weather details appear dynamically
(city, date, temperature, weather type, high/low).
● Console logs show API responses for debugging.
🧩 Extension Task
Students are required to:
● Add an input validation to prevent empty searches.
● Display a custom background image based on the weather type (e.g., sunny, rainy).