Follow our tutorial to build a weather app from scratch. Develop a web-based forecast system using HTML, CSS, and JavaScript.
Table of Contents
Weather apps have become an essential part of our daily lives, offering real-time updates on weather conditions that help us plan our activities and stay prepared for the day ahead. Have you ever wondered how these apps are developed? In this comprehensive tutorial, we'll take you through the step-by-step process of creating your very own weather app using the powerful trio of HTML, CSS, and JavaScript.
Weather impacts our decisions, from choosing the right outfit for the day to planning outdoor events. Learning how to build a weather app not only provides you with valuable coding skills but also empowers you to craft a tool that adds practical value to users' lives. Even if you're new to web development, fear not – we'll break down each stage into easily digestible segments, ensuring that you grasp every concept along the way.
As we embark on this journey together, you'll discover the art of translating data into a user-friendly interface. By the end of this tutorial, you'll have gained the knowledge and confidence to fetch real-time weather data from APIs, design an appealing and responsive user interface, and implement interactive features that elevate your app's functionality. Whether you're a coding enthusiast eager to expand your skill set or a beginner curious about the world of web development, this tutorial welcomes you to explore the exciting realm of weather app creation.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our weather app.
After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.
Let's break down each part of the code step by step:
1. <!DOCTYPE html>: This declaration defines the document type as HTML5, which is the latest version of HTML.
2. <html lang="en">: The <html> tag is the root element of an HTML document. The lang attribute is set to "en" (English), indicating that the primary language of the content is English.
3. <head>: This section contains metadata and resources that are used to configure and enhance the webpage but are not directly visible to the user.
- <meta charset="UTF-8" />: This meta tag specifies the character encoding of the document as UTF-8, which supports a wide range of characters and symbols from different languages.
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />: This meta tag sets the viewport configuration for responsive design. It ensures that the webpage is initially displayed at a 1:1 scale on various devices and adjusts the layout to fit the device's screen width.
- <title>Weather App</title>: This title element sets the title of the webpage, which is displayed in the browser's title bar or tab.
- <link rel="stylesheet" type="text/css" href="styles.css" />: This link tag references an external CSS (Cascading Style Sheets) file named "styles.css." The stylesheet is used to define the visual styles and layout of the webpage.
- <script src="script.js" defer></script>: This script tag references an external JavaScript file named "script.js." The defer attribute indicates that the script should be executed after the HTML content is parsed. JavaScript is used to add interactivity and dynamic behavior to the webpage.
4. <body>: This section contains the visible content of the webpage that users can see and interact with.
- <div class="card">: A <div> element with the class "card." It's a container used to group elements together for styling purposes, often used to create card-like layouts.
- <form id="form">: A <form> element with the ID "form." This is a container for input elements and defines a form that can be submitted to a server. In this case, it's likely used for user input.
- <input type="text" id="search" placeholder="Search by location" autocomplete="off" />: An <input> element of type "text." It's a text input field with the ID "search" and a placeholder "Search by location." The autocomplete attribute is set to "off" to disable browser suggestions.
- <main id="main"></main>: A <main> element with the ID "main." This is typically used to contain the main content of the webpage. It's likely that the weather information or results will be displayed here.
- </div>: Closes the "card" <div> element.
This is the basic structure of our weather app using HTML, and now we can move on to styling it using CSS.
Step 2 (CSS Code):
Once the basic HTML structure of the weather app is in place, the next step is to add styling to the weather app using CSS.
Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our weather app.
I'll break down the code and explain each part:
1. @import: This rule is used to import an external CSS file from the given URL. In this case, it imports font styles from the Google Fonts API for the "Poppins" font with different weights and styles.
2. body: This block of CSS rules targets the <body> element of the webpage.
- background-image: Sets the background of the body to an SVG image encoded as a data URL. The SVG defines a background pattern and a white mask, creating a visually appealing background.
- background-size: Specifies that the background image should cover the entire viewport.
- font-family: Sets the font family for text content to "Poppins" and then falls back to a generic sans-serif font.
- display: Makes the body a flex container.
- flex-direction: Sets the flex container's children to be stacked in a column.
- align-items and justify-content: Center the content both vertically and horizontally.
- margin: Removes margin around the body.
- height: Sets the body's height to 100% of the viewport's height.
3. ::placeholder: Targets the placeholder text of input elements.
- color: Sets the color of the placeholder text to white (#fff).
4. input: Styles all input elements.
- background-color: Sets the background color of the input to a dark gray (#575757).
- border: Removes the border around the input.
- border-radius: Rounds the corners of the input.
- box-shadow: Adds a subtle shadow around the input.
- font-family and font-size: Inherits the font family and sets the font size.
- padding: Adds spacing inside the input.
- min-width: Specifies a minimum width for the input.
- color: Sets the text color to white (#fff).
- transition: Adds a smooth transition effect when properties change.
5. input#search:hover: Targets the search input when hovered.
- background: Changes the background color on hover.
6. input:focus: Targets the search input when focused (clicked or tabbed into).
- outline: Removes the default focus outline.
- align-items, margin-bottom, and padding-left: Adjusts spacing and alignment when the input is focused.
7. .weather: Targets elements with the class "weather".
- font-size: Sets a larger font size.
- text-align: Centers the text.
8. .weather h2: Targets <h2> elements inside elements with the class "weather".
- display: Makes the <h2> and its content a flex container.
- align-items, margin-bottom, and padding-left: Adjusts spacing and alignment.
9. .card: Targets elements with the class "card".
- background: Sets a semi-transparent black background.
- width and max-width: Sets the width of the card.
- height: Sets the height of the card.
- padding: Adds spacing inside the card.
- text-align: Centers the text.
- border-radius: Rounds the corners.
- color: Sets the text color to white.
10. .more-info p and .more-info span: Targets elements inside the "more-info" class.
- font-size: Sets font size and font weight for specific elements.
This will give our weather app an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");
body {
background-image: url("https://images.unsplash.com/photo-1483728642387-6c3bdd6c93e5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2076&q=80");
background-size: cover;
font-family: "Poppins", sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
height: 100vh;
}
::placeholder {
color: #fff;
}
input {
background-color: #575757;
border: none;
border-radius: 25px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
font-family: inherit;
font-size: 1rem;
padding: 1rem;
min-width: 300px;
color: #fff;
transition: 0.2s;
}
input#search:hover {
background: #65747b;
}
input:focus {
outline: none;
align-items: center;
margin-bottom: 0;
padding-left: 85px;
}
.weather {
font-size: 2rem;
text-align: center;
}
.weather h2 {
display: flex;
align-items: center;
margin-bottom: 0;
padding-left: 90px;
}
.card {
background: #000000b2;
width: 100%;
max-width: 470px;
height: 70%;
padding: 2.5em;
text-align: center;
border-radius: 30px;
color: white;
}
.more-info p {
font-size: 20px;
}
.more-info span {
font-weight: 600;
}
Step 3 (JavaScript Code):
Finally, we need to create a function in JavaScript that fetches weather information from the OpenWeatherMap API and displays it on a webpage.
Here's a breakdown of the code:
1. const apikey = "YOUR API KEY";: This line sets up a constant variable to hold your OpenWeatherMap API key, which is required to make requests to the API.
2. DOM Elements:
- const main = document.getElementById("main");: Gets the DOM element with the ID "main", which will be used to display the weather information.
- const form = document.getElementById("form");: Gets the DOM element with the ID "form", which represents the search form for entering a city.
- const search = document.getElementById("search");: Gets the DOM element with the ID "search", which is the input field where the user can type a city name.
3. URL Generation:
- const url = (city) => ...: Defines a function that generates the URL for making API requests to OpenWeatherMap based on the provided city name. The city parameter is interpolated into the URL along with the API key.
4. async function getWeatherByLocation(city): This asynchronous function fetches weather data from the OpenWeatherMap API for the specified city. It uses the fetch function to make a request and awaits the response. The response data is then converted to JSON format. The addWeatherToPage function is called with the JSON data to display the weather information on the page.
5. function addWeatherToPage(data): This function takes the weather data received from the API and dynamically generates HTML elements to display the weather information on the webpage. It extracts temperature, humidity, wind speed, and weather icon data from the response data and inserts them into the HTML structure.
6. function KtoC(K): A utility function that converts temperature from Kelvin to Celsius by subtracting 273.15.
7. Event Listener:
- form.addEventListener("submit", (e) => { ... }): Adds an event listener to the form's submit event. When the form is submitted (e.g., by pressing Enter after entering a city name), the event listener prevents the default form submission behavior and retrieves the city entered by the user. If a city is provided, the getWeatherByLocation function is called to fetch and display the weather information for that city.
Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.
const apikey = "YOUR API KEY";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
const url = (city) =>
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`;
async function getWeatherByLocation(city) {
const resp = await fetch(url(city), { origin: "cors" });
const respData = await resp.json();
console.log(respData);
addWeatherToPage(respData);
}
function addWeatherToPage(data) {
const temp = KtoC(data.main.temp);
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
const weather = document.createElement("div");
weather.classList.add("weather");
weather.innerHTML = `
<h2><img src="https://openweathermap.org/img/wn/${
data.weather[0].icon
}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${
data.weather[0].icon
}@2x.png" /></h2>
<small>${data.weather[0].main}</small>
<div class="more-info">
<p>Humidity : <span>${humidity}%</span></p>
<p>Wind speed : <span>${+Math.trunc(windSpeed * 3.16)}km/h</span></p>
</div>
`;
// cleanup
main.innerHTML = "";
main.appendChild(weather);
}
function KtoC(K) {
return Math.floor(K - 273.15);
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const city = search.value;
if (city) {
getWeatherByLocation(city);
}
});
Final Output:
Conclusion:
Congratulations! You've successfully built a weather app using HTML, CSS, and JavaScript. You've learned how to structure a web app, style it, and add interactivity. Keep exploring and enhancing your web development skills.
By following these steps, you'll be able to create your own weather app using HTML, CSS, and JavaScript. Whether you're a beginner or looking to expand your coding skills, this tutorial provides a solid foundation for developing web applications. Don't hesitate to experiment and add your own unique features to make your weather app stand out!
Credit: ZeroOctave
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊