Introduction
If you’re learning JavaScript and looking for a fun project to practice your skills, this tutorial is perfect for you. In just 15 minutes, you’ll learn how to build a weather app in JavaScript using real-time data from the OpenWeather API.
This project is beginner-friendly and doesn’t require any advanced setup or frameworks. All you need is:
- A basic understanding of HTML, CSS, and JavaScript
- A code editor like VS Code
- A browser to test your app
We’ll use the OpenWeather API to get up-to-date weather information. This is a great way to practice working with APIs, handling JSON data, and updating the DOM dynamically with JavaScript.
Why Build a Weather App?
A weather app might seem simple, but it’s one of the best beginner projects to strengthen your JavaScript skills. Here’s why:
Learn API Calls (fetch, async/await)
Working with APIs is a must-have skill for modern web developers. In this project, you’ll use the fetch()
method and async/await to get real-time weather data from the OpenWeather API. This teaches you how to:
- Connect your app to external data sources.
- Handle JSON responses from APIs.
- Manage asynchronous operations in JavaScript.
For example, when a user searches for “Toronto,” your app will send a request to OpenWeather and display the live weather details.
Work With User Input and Error Handling
You’ll also learn how to:
- Capture user input from a text field.
- Validate it (so the app doesn’t break with empty or invalid entries).
- Show friendly error messages when something goes wrong (like entering a city that doesn’t exist).
This is a critical skill for building user-friendly applications.
Create Something Useful and Portfolio-Worthy
Unlike small code exercises, this is a real-world project. By the end, you’ll have a working app that you can:
- Showcase in your portfolio.
- Share with friends or colleagues.
- Customize further to demonstrate your growing skills.
Prerequisites
Before you start, make sure you have:
- Basic knowledge of HTML, CSS, and JavaScript (even a little is enough).
- A code editor like VS Code and a modern browser (Chrome or Firefox).
- A free OpenWeather API account to get your API key (we’ll guide you through this).
- Optional: Familiarity with browser DevTools for debugging (
Ctrl+Shift+I
orCmd+Option+I
).
That’s all! You’re ready to build a weather app in JavaScript and fetch real-time data.
Project Overview
This project is a simple weather app that lets users check the current weather for any city in the world. It’s clean, minimal, and beginner-friendly.
Here’s what your app will do:
✅ Allow users to enter a city name in a search box.
✅ Fetch real-time weather data from the OpenWeather API.
✅ Display the following information on the page:
- 🌡️ Temperature (in Celsius)
- 🌥️ Weather description (like “clear sky” or “light rain”)
- 🌤️ A weather icon that matches the current condition
What It Will Look Like
Here’s a preview of the final app UI:
(Insert a clean screenshot or diagram of the app here—for now, imagine a centered white card with a city search box, a blue “Get Weather” button, and the weather results displayed below)
Even though it’s simple, this weather app will teach you how to:
- Work with APIs and JSON data.
- Update the DOM dynamically with JavaScript.
- Handle user input and errors gracefully.
By the end, you’ll have a working project that you can proudly add to your portfolio or share with friends.
Step 1 – Set Up Your Project
Let’s start by creating the basic setup for your weather app. This step will help you organize your files and prepare your workspace.
Create the Project Folder
- Create a new folder on your computer called
weather-app
. - Inside the
weather-app
folder, create the following three files:index.html
– This will hold the structure of your web page.style.css
– This will contain all the styling for your app.app.js
– This is where you’ll write the JavaScript code to fetch and display weather data.
For example:
📁 weather-app/
📄 index.html
📄 style.css
📄 app.js
You can create these files manually in your file explorer or directly in your code editor (like VS Code).
Project Folder Structure
Here’s what your folder structure should look like:
weather-app/
├── index.html
├── style.css
└── app.js
This simple structure keeps things organized and easy to manage as you build your weather app.
Now that your project folder is ready, let’s move on to adding the HTML structure for your app.
Step 2 – Build the HTML Structure
Now that your project folder is set up, let’s create the basic structure of your weather app in index.html
.
Here’s the full code for 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="container">
<h1>Weather App</h1>
<input type="text" id="cityInput" placeholder="Enter city name">
<button id="getWeatherBtn">Get Weather</button>
<div id="weatherResult"></div>
</div>
<script src="app.js"></script>
</body>
</html>
What This Does:
<input>
: Lets the user type a city name.<button>
: Triggers a function to fetch weather data when clicked.<div id="weatherResult">
: Displays the fetched weather information.
This is a clean and minimal layout to keep things simple while we focus on functionality.
Step 3 – Style the App with CSS
With the HTML ready, let’s make your app look clean and modern using CSS.
Open style.css
and add the following styles:
/* Reset default margins and set font */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background: linear-gradient(to right, #83a4d4, #b6fbff);
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
/* Style the container */
.container {
background: white;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
text-align: center;
max-width: 400px;
width: 100%;
}
/* Style the heading */
h1 {
margin-bottom: 20px;
color: #333;
}
/* Style input and button */
input[type="text"] {
width: 80%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 15px;
background-color: #007BFF;
border: none;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
/* Style the weather result display */
#weatherResult {
margin-top: 20px;
font-size: 1.1rem;
}
What This Does:
- Centers the app vertically and horizontally.
- Gives the app a clean card-style design.
- Styles the input and button for a modern look.
- Adds subtle hover effects for better user experience.
Your app now looks polished and is mobile-friendly by default.
Step 4 – Get Your OpenWeather API Key
To fetch live weather data, we need access to the OpenWeather API. This requires a free API key, which acts like a password that lets your app communicate with OpenWeather’s servers.
Follow these steps to get your API key:
1. Sign Up for a Free Account
- Go to OpenWeather’s website.
- Click Sign Up in the top right corner and create a free account.
2. Verify Your Email
- After signing up, check your email inbox for a verification link.
- Click the link to activate your OpenWeather account.
3. Generate an API Key
- Log in to your OpenWeather account.
- Go to the API Keys section in your dashboard.
- By default, you’ll see an API key already generated for you. It’s a long string of letters and numbers (like
abc123def456ghi789
). - Copy this API key—you’ll use it in your JavaScript file.
OpenWeather Dashboard Example
(Insert screenshot of the OpenWeather API dashboard showing where the API key is located)
4. Note About API Activation
It may take a few minutes for your API key to become active. If you get an error like “Invalid API key,” wait 10–15 minutes and try again.
Now that you have your API key, you’re ready to connect it to your weather app and start fetching real-time data.
Step 5 – Write JavaScript to Fetch Weather Data
Now it’s time to bring your weather app to life! You’ll write JavaScript code that:
- Listens for user interaction (button click)
- Fetches weather data from OpenWeather API
- Displays the weather info on your page
Add Event Listener
First, let’s connect the Get Weather button to a function that runs when clicked. This function will read the city name entered by the user and start fetching the weather data.
Add this code to your app.js
file:
// Select the button and add a click event listener
document.getElementById('getWeatherBtn').addEventListener('click', () => {
// Get the city input value
const city = document.getElementById('cityInput').value.trim();
// Call the function to fetch weather data
if (city) {
getWeather(city);
} else {
alert('Please enter a city name.');
}
});
What’s happening here?
- When the button is clicked, we grab the city name from the input field.
- If the input is empty, we show an alert asking the user to enter something.
- If the city name is valid, we call the
getWeather
function (which we will create next).
Fetch Data from OpenWeather API
Next, let’s write the getWeather
function that fetches weather data using JavaScript’s fetch()
and async/await
. This makes your code easier to read and handle asynchronous calls.
Here’s the full function you can add to app.js
(replace 'YOUR_API_KEY'
with your actual OpenWeather API key):
const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeather API key
async function getWeather(city) {
const weatherResult = document.getElementById('weatherResult');
weatherResult.innerHTML = 'Loading...'; // Show loading text while fetching
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
);
if (!response.ok) {
throw new Error('City not found');
}
const data = await response.json();
displayWeather(data);
} catch (error) {
weatherResult.innerHTML = `<p style="color: red;">${error.message}</p>`;
}
}
Explanation:
- We build the API URL by inserting the city name and API key.
units=metric
means the temperature will be in Celsius.- If the city isn’t found, we throw an error to catch it later.
- On success, we pass the weather data to
displayWeather()
(which you’ll write next). - If there’s an error, we display a red error message on the page.
Display Weather Data on the Page
Finally, let’s show the weather info inside the weatherResult
div by creating a helper function displayWeather
.
Add this function to your app.js
:
function displayWeather(data) {
const { name, main, weather } = data;
const iconUrl = `https://openweathermap.org/img/wn/${weather[0].icon}@2x.png`;
document.getElementById('weatherResult').innerHTML = `
<h2>${name}</h2>
<img src="${iconUrl}" alt="${weather[0].description}">
<p style="text-transform: capitalize;">${weather[0].description}</p>
<p>🌡️ Temperature: ${main.temp} °C</p>
`;
}
How this works:
- Extract city name, temperature, and weather description from the API response.
- Construct the icon URL using the icon code provided by OpenWeather.
- Update the
weatherResult
div with formatted HTML including an icon and weather details. - Capitalize the weather description for readability.
Test it out!
- Save your
app.js
file. - Open your
index.html
in a browser. - Type a city name like “London” or “New York” and click Get Weather.
- You should see the current temperature, description, and an icon appear!
Step 6 – Test Your Weather App
Now that your app is ready, it’s time to test and make sure everything works smoothly.
How to test your weather app:
- Try entering valid city names like “London,” “Tokyo,” or “Toronto.” You should see the temperature, weather description, and icon update accordingly.
- Test invalid inputs such as gibberish or empty entries. The app should show an error message like “City not found” or prompt you to enter a city.
- Open your browser’s developer console (press
F12
orCtrl+Shift+I
/Cmd+Option+I
) and watch for any error messages if something doesn’t work. Console errors give clues for troubleshooting. - Refresh the page and try searching for different cities to see how the app behaves with repeated queries.
Pro tip:
Try searching cities worldwide—big cities, small towns, or places you want to visit someday. This helps ensure your app works for various locations.
Bonus – Make It Even Better
Once your basic weather app is working, you can add cool features to make it more useful and impressive. Here are some ideas to explore:
Toggle Between Celsius and Fahrenheit
- Add a button or switch to let users choose their preferred temperature unit.
- Modify the API request or convert temperatures in JavaScript accordingly.
Add Background Images Based on Weather
- Change the app’s background image dynamically depending on weather conditions (e.g., sunny, rainy, snowy).
- This makes the app more visually appealing and immersive.
Show a 5-Day Weather Forecast
- Use OpenWeather’s forecast API to display weather predictions for the next few days.
- This adds more depth and usefulness to your app.
Detect User’s Current Location
- Use the browser’s Geolocation API to get the user’s coordinates automatically.
- Fetch and display weather for their current location without typing a city name.
Next Steps
Great job on building your first weather app using JavaScript and the OpenWeather API! Now that you’ve completed this project, here’s what you can do next to keep growing your skills:
Subscribe to StayAhead.tech
Stay updated with more hands-on projects, tutorials, and practical tips by subscribing to StayAhead.tech. We regularly share beginner-friendly guides to help you become a confident developer.
Try Another Beginner Project
Keep the momentum going by building other simple apps like:
- A To-Do List app to practice working with arrays and local storage.
- A Calculator app to sharpen your logic and event handling skills.
These projects will reinforce what you’ve learned and introduce you to new concepts.
Share Your Weather App
Show off your work by:
- Uploading your code to GitHub and sharing the link on social media or developer communities.
- Sharing the live app with friends or mentors and asking for feedback.
Sharing your projects is a great way to build your portfolio and get noticed by potential employers.
Keep experimenting, learning, and building — you’re on the right path to mastering JavaScript and web development!