Building a Weather Forecast Application with HTML, CSS, and JavaScript: A Step-by-Step Guide

Wasiu Akindoyin
Coinmonks
Published in
8 min readApr 2, 2024

--

· Introduction
· Project Overview
· Prerequisites
· Features of the Weather Forecast Application
· Code Structure
Step 1. HTML Structure:
Step 2. CSS Styling:
Step 3. JavaScript Logic:
· Testing and Debugging
· Lessons Learned
· Deployment
· Directions on How to use the Application
· Future Improvements
· Conclusion

Introduction

This guide will walk you through the process of creating an interactive weather forecast application using HTML, CSS, and JavaScript. Users will be able to access current weather conditions and forecasts for any location around the world.

Project Overview

The weather forecast app will have a simple and user-friendly interface. Users can input a location in a search bar, and the app will show the current weather conditions for that area. I used the OpenWeather API to retrieve weather information based on the user’s location input. The app also offers extra information, including temperature, humidity, wind speed, a weather icon depicting the current conditions, and a background image of the searched location.

Prerequisites

To build this Weather forecast application, you’ll need a basic understanding of HTML, CSS, and JavaScript. You should be familiar with HTML for structuring the application, CSS for styling it, and JavaScript for implementing the logic of the application.

A text editor or IDE (e.g., Visual Studio Code) is required for writing code, and a web browser is needed for testing. Optional prerequisites include a GitHub account for hosting the application.

Features of the Weather Forecast Application

In this project, you will create a weather forecast app with the following features:

  • Location-based Weather: Users can enter a location (city) to view the current weather conditions and forecast for that area.
  • Current Weather Display: The application shows the current temperature, weather conditions (e.g., sunny, rainy, cloudy), humidity, wind speed, and visibility.
  • Weather Icons: Use weather icons (e.g., sun, cloud, rain) to represent the weather conditions for easy understanding visually.
  • Responsive Design: Ensure the application is responsive and works well on different devices and screen sizes.

Code Structure

Create a new folder for your project, name the folder as you wish, and inside it, create three files named index.html, style.css, and script.js. These files will serve as the foundation for your project. Now open the folder in a text editor or IDE (e.g., Visual Studio Code) and follow the steps below:

Step 1. HTML Structure:

Open theindex.html file and paste the following HTML code for the Weather forecast application:

<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Weather App</title>
</head>
<body>
<div class="card">
<div class="search">
<input type="text" class="search-bar" placeholder="Search">
<button><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1.5em" width="1.5em" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10.442 10.442a1 1 0 011.415 0l3.85 3.85a1 1 0 01-1.414 1.415l-3.85-3.85a1 1 0 010-1.415z" clip-rule="evenodd"></path><path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 100-11 5.5 5.5 0 000 11zM13 6.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z" clip-rule="evenodd"></path></svg></button>
</div>

<div class="weather loading">
<h1 class="city">Weather in Lagos</h1>
<h1 class="temp">51°C</h1>
<div class="flex">
<img src="//cdn.weatherapi.com/weather/64x64/day/116.png" alt="" class="icon">
<div class="description">Cloudy</div>
</div>
<div class="humidity">Humidity:60%</div>
<div class="wind">Wind Speed:6.2 km/hr</div>
</div>
</div>

<script src="script.js"></script>

</body>
</html>

The HTML code above sets up the weather application interface with a search bar and weather information display. It includes elements for input, button, city name, temperature, weather icon, description, humidity, and wind speed.

The design features a card layout with search functionality and weather details for a specific city. It also includes a link to an external CSS file and a JavaScript file.

Step 2. CSS Styling:

Open thestyle.css file and paste the following CSS code to style the Weather forecast application:

body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: darkgrey;
margin: 0;
font-size: 120%;
background-image: url("https://source.unsplash.com/1600x900/?nature,landscape");
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}

.card {
background-color: black;
padding: 2em;
color: white;
border-radius: 30px;
width: 100%;
max-width: 420px;
margin: 1em;
box-shadow: 1px 3px 5px rgba(141, 138, 138, 0.1);
}

.search {
display: flex;
align-items: center;
justify-content: center;
}

input.search-bar {
border: none;
outline: none;
padding: 0.4em 1em;
border-radius: 30px;
background-color: #534b4b;
color: white;
font-size: 120%;
width: calc(100% - 100px);
font-family: 'Roboto';
letter-spacing: 2px;
}

button {
margin: 0.5em;
border-radius: 50%;
border: none;
height: 3em;
width: 3em;
outline: none;
background-color: #534b4b;
color: white;
cursor: pointer;
transition: 0.3s ease-in-out;
}

button:hover {
background-color: #9b7979;
}

.weather {
font-weight: bold;
}

.weather.loading {
visibility: hidden;
max-height: 20px;
position: relative;
}

.weather.loading::after {
position: absolute;
top: 0;
color: white;
visibility: visible;
content: "Page Loading...";
font-weight: bold;
left: 30px;
}

h1.city {
letter-spacing: 2px;
text-transform: uppercase;
font-size: 1.3em;
}

h1.temp {
margin: 0;
margin-bottom: 0.5em;
font-size: 1.3em;
}

.flex {
display: flex;
align-items: center;
margin-left: -10px;
margin-bottom: 0.5em;
}

.flex .description {
text-transform: capitalize;
margin-left: 8px;
}

.humidity {
font-size: 1.2em;
margin-bottom: 0.5em;
}

@media screen and (max-width: 420px) {
.card {
border-radius: 35px;
max-width: 320px;
}

input.search-bar {
padding: 0.3em 0.8em;
border-radius: 30px;
background-color: #534b4b;
color: white;
width: calc(100% - 100px);
letter-spacing: 1px;
}
}

The CSS code above styles the weather application with a centered layout, a dark grey background, and a background image from Unsplash. It uses a flexbox for alignment, sets card styles with black background and white text, and styles input and button elements. The loading animation is hidden by default and displayed with a message when active. Media queries adjust styles for smaller screens.

Step 3. JavaScript Logic:

Open thescript.js file and add functionality to the Weather forecast application using the following JavaScript code:

let cityEl = document.querySelector(".city");

let iconEl = document.querySelector(".icon");

let descriptionEl = document.querySelector(".description");

let temperatureEl = document.querySelector(".temp");

let humidityEl = document.querySelector(".humidity");

let windEl = document.querySelector(".wind");

let searchBar = document.querySelector(".search-bar");

let searchEl = document.querySelector(".search button");

let weatherEl = document.querySelector(".weather");

let weather = {
"apikey": "a6f6fef1470f473cb0694459230605",

fetchWeather: function (city) {
fetch("http://api.weatherapi.com/v1/current.json?key=a6f6fef1470f473cb0694459230605%20&q=" + city + "&aqi=no").then((response) => response.json()).then((data) => this.displayWeather(data));
},

displayWeather: function (data) {
const { name } = data.location;

const { icon, text } = data.current.condition;

const { temp_c, humidity } = data.current;

const { wind_kph } = data.current;

cityEl.innerText = `Weather in ${name}`;

iconEl.src = icon;

descriptionEl.innerText = text;

temperatureEl.innerText = `Temperature: ${temp_c}°C`;

humidityEl.innerText = `Humidity: ${humidity}%`;

windEl.innerText = `Wind Speed: ${wind_kph} km/hr`;

weatherEl.classList.remove("loading");

document.body.style.backgroundImage = "url('https://source.unsplash.com/1600x900/?" + name + "')";
},

search: function () {
this.fetchWeather(searchBar.value);
}
};

searchEl.addEventListener("click", () => {
console.log("Clicked!");
weather.search();
});

searchBar.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
weather.search();
}
});

weather.fetchWeather("Lagos");

The JavaScript code above defines an object called weather that handles fetching and displaying weather data based on a city input. It uses the fetch API to make requests to a weather API (api.weatherapi.com) and updates the DOM with the fetched data.

It also includes event listeners for a search button and a search bar to allow users to search for weather data for a specific city. Additionally, it changes the background image based on the searched city. The default weather information for Lagos is fetched when the page loads.

Testing and Debugging

To test the application in your web browser, you can follow these steps:

  1. Open the HTML File: Make sure you have saved all your HTML, CSS, and JavaScript files in the same folder as stated earlier. Then, open the HTML file in your web browser by double-clicking on it. This will open the file in your default web browser.
  2. Inspect Element: Once the app is loaded in the browser, right-click on the page and select “Inspect” or press “Ctrl+Shift+I” to open the developer tools. This will allow you to see any errors in the console and inspect elements on the page.
  3. Test Functionality: Interact with your app to test its functionality. This will help you identify any bugs or issues in your code.
  4. Debugging: If you encounter any errors or issues, use the console in the developer tools to debug your JavaScript code. Look for error messages and line numbers to pinpoint where the issue is occurring.
  5. Make Changes: If you need to make changes to your code, go back to your code editor, make the necessary adjustments, save the file, and then refresh the browser to see the changes reflected in your app.

Lessons Learned

I now understand the importance of planning and designing the logic of an application before beginning the coding process. I have also enhanced my knowledge of CSS styles, JavaScript events, and DOM manipulation, which are all important for creating interactive web applications.

Deployment

The project for the Weather forecast application is available on GitHub Pages and can be accessed online by clicking on the following link:

Test the Application: https://wasiu-akindoyin.github.io/Weather-Forecast-Web-Application/

You can access the GitHub repository here to view or contribute to the source code.

Directions on How to use the Application

Follow these steps to use the weather forecast application:

  1. Open the application in your web browser by visiting the GitHub Pages URL provided for the Weather forecast application above.
  2. Once the app loads, you will see a search bar at the top. Enter the name of the city for which you want to check the weather and press Enter, or click, the search button.
  3. The app will fetch the current weather data for the specified city from the WeatherAPI and display it on the screen. You will see the city name, current temperature, weather description, humidity, and wind speed.
  4. By scrolling down, you can also see a background image associated with the city. The background image will change depending on the city you are searching for.
  5. To search for weather in a different city, simply enter a new city name in the search bar and press Enter, or click, the search button again.
  6. Enjoy using the weather app to check the current weather conditions in different cities!

Future Improvements

In the future, I plan to add more features, such as:

  • Location Detection: Implement geolocation to automatically detect and display weather for the user’s current location.
  • Local Storage: Save the user’s preferred location or settings in local storage to remember their choices between visits.
  • Error Handling: Add error handling for failed API requests or invalid user input.
  • Multiple Locations: Enable users to add and switch between multiple locations for weather information.

Conclusion

Building this weather forecast application using HTML, CSS, and JavaScript was a fulfilling experience for me. We have gained knowledge on integrating APIs, managing asynchronous operations, and developing a responsive web application. This application offers a useful service to users, enabling them to conveniently access weather information for any location.

--

--

Wasiu Akindoyin
Coinmonks

Front-end Developer | Technical Writer | Simplifying complex software concepts through code and real life analogies.