Have you ever wondered how to make a weather app that shows you the current temperature, humidity, wind speed, and weather condition of any city in the world? Well, wonder no more, because in this article, I will show you how to do it with just a few lines of JavaScript code and a free weather API.
What is a Weather App?
A weather app is a web application that uses a weather API (Application Programming Interface) to get the weather data from a server and display it on the web page. A weather API is a service that provides weather information for different locations based on various parameters, such as city name, zip code, latitude, longitude, etc.
A weather app can be very useful for travelers, farmers, outdoor enthusiasts, or anyone who wants to know the weather forecast for their destination. It can also be a fun and educational project for beginners who want to learn how to use APIs and JavaScript to create dynamic web pages.
Why Do We Need a Weather App?
There are many reasons why we might want to build a weather app, such as:
To learn how to use APIs and JavaScript to fetch and display data from a server.
To practice our HTML, CSS, and JavaScript skills and create a beautiful and responsive user interface.
To impress our friends, family, or potential employers with our coding abilities and creativity.
To have fun and enjoy the process of making something cool and useful.
How Do We Build a Weather App?
To build a weather app, we need three main components:
A weather API that provides us with the weather data for any location.
A HTML file that defines the structure and content of our web page.
A CSS file that styles and positions the elements on our web page.
A JavaScript file that connects to the weather API, gets the weather data, and updates the web page accordingly.
Let’s see how we can create each of these components step by step.
Step 1: Choose a Weather API
There are many weather APIs available on the internet, but for this project, we will use the OpenWeatherMap API, which is free and easy to use. To use this API, we need to sign up for an account and get an API key, which is a unique code that identifies us as a valid user of the service.
To get an API key, we need to go to the OpenWeatherMap website, click on the “Sign Up” button, fill in the required details, and verify our email address. Then, we need to go to the API keys tab and copy the default API key that is generated for us.
We will use this API key to make requests to the OpenWeatherMap API and get the weather data for any location. The API key should be kept secret and not shared with anyone, as it can be used to access our account and data.
Step 2: Create a HTML File
Next, we need to create a HTML file that will contain the basic structure and content of our web page. We can use any text editor or IDE (Integrated Development Environment) to create and edit our HTML file, such as Visual Studio Code, Sublime Text, Atom, etc.
We can name our HTML file anything we want, but for simplicity, we will call it index.html. We can save it in any folder or directory on our computer, but we need to remember its location, as we will need to open it in a web browser later.
The HTML file should have the following basic structure:
<!-- index.html -->
<div class="container">
<!-- Input field for the user to enter a city -->
<input type="text" id="city-input" placeholder="Enter a city name">
<!-- Button to trigger the weather search -->
<button id="search-button">Search</button>
<!-- Container for displaying weather data -->
<div id="weather-data">
<!-- City name -->
<h1 id="city-name"></h1>
<!-- Left section for weather icon and description -->
<div class="left-section">
<img id="weather-icon" src="" alt="">
<p id="weather-description"></p>
</div>
<!-- Right section for temperature, humidity, and wind speed -->
<div class="right-section">
<p id="temperature"></p>
<p id="humidity"></p>
<p id="wind-speed"></p>
</div>
</div>
</div>
<!-- FontAwesome script for adding icons -->
<script src="https://kit.fontawesome.com/9ca3ef8694.js" crossorigin="anonymous"></script>
Let’s explain what each part of the HTML code does:
<div class="container">
: This is the main container that wraps around all the elements. It helps to structure and organize the content on the webpage. It has the class name "container," which can be used for styling.<input type="text" id="city-input" placeholder="Enter a city name">
: This is an input field where users can type the name of a city. The type="text" attribute indicates that it's a text input. It has an id of "city-input," which can be used to identify and manipulate this input element using JavaScript. The placeholder attribute provides a hint or example text to guide the user, saying "Enter a city name."<button id="search-button">Search</button>
: This is a button element with the text "Search." It has an id of "search-button," allowing JavaScript to target and handle clicks on this button.<div id="weather-data">
: This is another container that holds the weather-related information. It has an id of "weather-data" for easy identification.<h1 id="city-name"></h1>
: This heading element is where the name of the city will be displayed. It has an id of "city-name."<div class="left-section">
and<div class="right-section">
: These two div elements inside "weather-data" divide the weather information into two sections: left and right.<img id="weather-icon" src="" alt="">
: This img element is for displaying the weather icon. The id is "weather-icon," and it starts with an empty source (src=""). JavaScript will dynamically update this source to show the appropriate weather icon.<p id="weather-description"></p>
: This paragraph element is for displaying a brief description of the weather, such as "Sunny" or "Cloudy." It has an id of "weather-description."<p id="temperature"></p>
,<p id="humidity"></p>
,<p id="wind-speed"></p>
: These three paragraphs are for displaying specific weather information. "temperature" will show the temperature, "humidity" for humidity, and "wind-speed" for wind speed.
Step 3: Create a CSS File
Now that we have created the HTML file, we need to create a CSS file that will style and position the elements on our web page.
We can name our CSS file anything we want, but for consistency, we will call it style.css. We need to save it in the same folder as the HTML file, so we can link them together.
The CSS file should have the following basic style rules:
/* style.css */
/* Select the body element and apply some general styles */
body {
background-color: #e0f0ff;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
}
/* Select the container element and apply some layout and positioning styles */
.container {
width: 80vw;
height: 80vh;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 20px;
border: 5px solid #a0c0e0;
border-radius: 20px;
box-shadow: 10px 10px 20px #808080;
}
/* Select the input element and apply some style and layout styles */
#city-input {
width: 60%;
height: 5%;
font-size: 1.5em;
padding: 10px;
border: 2px solid #a0c0e0;
border-radius: 0.6rem;
display: block;
margin: auto;
}
/* Select the button element and apply some style and layout styles */
#search-button {
width: 20%;
height: 15%;
font-size: 1.5em;
padding: 10px;
border: 2px solid #a0c0e0;
border-radius: 10px;
display: block;
margin: 10px auto;
transition: background-color 0.5s, cursor 0.5s;
}
/* Select the button element when it is hovered and apply some style changes */
#search-button:hover {
background-color: #a0c0e0;
cursor: pointer;
}
/* Select the weather-data element and apply some layout and positioning styles */
#weather-data {
width: 80%;
max-height: 60%;
margin: auto;
padding: 20px;
border: 2px solid #a0c0e0;
border-radius: 10px;
box-shadow: 5px 5px 10px #808080;
display: none;
}
/* left section of weather container */
.left-section {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
/* right section of weather container */
.right-section {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
/* Select the city-name element and apply some style and layout styles */
#city-name {
font-size: 2em;
font-weight: bold;
text-align: center;
}
/* Select the weather-description element and apply some style and layout styles */
#weather-description {
font-size: 1.5em;
text-align: center;
}
/* Select the temperature element and apply some style and layout styles */
#temperature {
font-size: 1.5em;
text-align: center;
box-shadow: 5px 5px 10px #808080;
border-radius: 10px;
padding: 15px;
}
/* Select the humidity element and apply some style and layout styles */
#humidity {
font-size: 1.5em;
text-align: center;
box-shadow: 5px 5px 10px #808080;
border-radius: 10px;
padding: 15px;
}
/* Select the wind-speed element and apply some style and layout styles */
#wind-speed {
font-size: 1.5em;
text-align: center;
box-shadow: 5px 5px 10px #808080;
border-radius: 10px;
padding: 15px;
}
#temperature:hover, #humidity:hover, #wind-speed:hover {
border: 2px solid #a0c0e0;
}
This is how the CSS code styles and positions the elements on our web page. You can see the result by opening the index.html file in a web browser. You can also modify the CSS code to change the colors, sizes, fonts, or any other style properties as you like.
Step 4: Create a JavaScript File
Finally, we need to create a JavaScript file that will connect to the weather API, get the weather data, and update the web page accordingly.
We can name our JavaScript file anything we want, but for consistency, we will call it script.js. We need to save it in the same folder as the HTML file, so we can link them together.
The JavaScript file should have the following basic code:
// script.js
// Retrieve HTML elements for user input, buttons, and weather data
const cityInput = document.getElementById("city-input");
const searchButton = document.getElementById("search-button");
const weatherData = document.getElementById("weather-data");
const cityName = document.getElementById("city-name");
const weatherIcon = document.getElementById("weather-icon");
const weatherDescription = document.getElementById("weather-description");
const temperature = document.getElementById("temperature");
const humidity = document.getElementById("humidity");
const windSpeed = document.getElementById("wind-speed");
// OpenWeatherMap API URL and API key
const baseURL = "https://api.openweathermap.org/data/2.5/weather";
const apiKey = "18ebd2752d8e0e48922317c04caa2606";
// Add click event listener to the search button
searchButton.addEventListener("click", getWeather);
// Define the getWeather function to fetch weather data
function getWeather() {
const city = cityInput.value;
// Check if a city name is provided
if (city) {
const url = `${baseURL}?q=${city}&appid=${apiKey}&units=metric`;
console.log(url); // Log the URL to the console
// Fetch weather data from the OpenWeatherMap API
fetch(url)
.then((response) => response.json())
.then((data) => displayWeather(data))
.catch((error) => console.error(error));
} else {
// Display an alert if no city name is provided
alert("Please enter a valid city name");
}
}
// Define the displayWeather function to show weather information on the webpage
function displayWeather(data) {
// Extract relevant information from the API response
const name = data.name;
const icon = data.weather[0].icon;
const description = data.weather[0].description;
const temp = data.main.temp;
const humid = data.main.humidity;
const wind = data.wind.speed;
// Update HTML elements with weather information
cityName.innerHTML = name;
weatherIcon.src = `https://openweathermap.org/img/wn/${icon}.png`;
weatherDescription.innerHTML = description;
// Display temperature, humidity, and wind speed with FontAwesome icons
temperature.innerHTML = `Temperature <i class="fa-solid fa-temperature-high"></i> <br>${temp} °C`;
humidity.innerHTML = `Humidity <i class="fa-solid fa-cloud-meatball"></i> <br>${humid} %`;
windSpeed.innerHTML = `Wind Speed <i class="fa-solid fa-wind"></i> <br>${wind} m/s`;
// Display the weather data section on the webpage
weatherData.style.display = "block";
}
Let’s explain what each part of the JavaScript code does:
Variable Declarations:
-
cityInput
,searchButton
,weatherData
,cityName
,weatherIcon
,weatherDescription
,temperature
,humidity
, andwindSpeed
are variables that store references to various HTML elements.
API Configuration:
baseURL
is set to the base URL of theOpenWeatherMap
API.apiKey
is your unique API key, allowing access toOpenWeatherMap's
data.
Event Listener:
searchButton
has an event listener attached to it, listening for a click event.When the button is clicked, it triggers the
getWeather
function.
getWeather Function:
Retrieves the value entered in the city input field
(cityInput)
.Checks if a city is entered. If not, displays an alert asking for a valid city name.
If a city is entered, constructs the API URL with the city name, API key, and units set to metric.
Logs the constructed URL to the console for debugging.
Uses the fetch function to make an API request.
Handles the response
asynchronously
usingpromises
(then and catch).
displayWeather Function:
Takes the
JSON data
returned by the API as a parameter.Extracts relevant weather information from the data
(city name, weather icon, description, temperature, humidity, and wind speed)
.Updates the HTML content of various elements with the extracted information.
Sets the source of the
weatherIcon
element to the URL of the weather icon.Uses
Font Awesome icons
to enhance the visual representation of temperature, humidity, and wind speed.Displays the weather data container
(weatherData)
by setting its style property to"block"
.
FontAwesome Icons:
-
FontAwesome
icons are used to visually represent temperature, humidity, and wind speed in thedisplayWeather
function.
Alert for Invalid Input:
- If the user clicks the search button without entering a city name, an alert prompts them to provide a valid city name.
This JavaScript code fetches weather data from the OpenWeatherMap API, updates the HTML to display the information, and adds visual elements with FontAwesome icons for a more engaging user experience.
What Did We Learn?
In this article, we learned how to build a weather app with JavaScript that allows users to enter a city name and displays the current weather information using a free weather API. We learned how to:
Use JavaScript to connect to the weather API, get the weather data, and update the web page accordingly
Use the fetch method to make API requests and handle promises
Use the template literal syntax to create strings that can include variables and expressions
Use the addEventListener method to attach functions to elements that will be executed when certain events occur
Use the innerHTML and src properties to modify the HTML content and source of the elements
We also learned some basic concepts of web development, such as:
APIs (Application Programming Interfaces)
JSON (JavaScript Object Notation)
Promises
Arrow functions
CLICK Here to see the Final Output.
Conclusion
Congratulations! You have successfully built a weather app with JavaScript that shows you the current weather information of any city in the world. You have also learned some useful skills and concepts that you can apply to other web development projects. I hope you enjoyed this article and found it helpful and interesting.
If you liked this article, please give it a thumbs up, share it with your friends, leave a comment, and follow me for more articles like this. Thank you for reading and happy coding! 😊
Top comments (0)