DEV Community

Cover image for Building a Complete Weather App from Scratch with HTML, CSS, and JavaScript: A Step-by-Step Guide
Odumosu Matthew
Odumosu Matthew

Posted on

Building a Complete Weather App from Scratch with HTML, CSS, and JavaScript: A Step-by-Step Guide

Creating a comprehensive weather app involves multiple steps, including fetching data from a weather API, designing the user interface, and handling user interactions. Here, we'll provide a step-by-step guide with code blocks on how to build a simple weather app using HTML, CSS, and JavaScript.

Step 1: Set Up Your Environment

Before you start coding, make sure you have a code editor (e.g., Visual Studio Code) and a web browser installed on your computer.

Step 2: Design the HTML Structure

Create an HTML file (e.g., index.html) and define the basic structure of your weather app. You can use the following HTML code as a starting point:



<!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="styles.css">
</head>
<body>
    <div class="container">
        <h1>Weather App</h1>
        <input type="text" id="locationInput" placeholder="Enter a city">
        <button id="searchButton">Search</button>
        <div class="weather-info">
            <h2 id="location"></h2>
            <p id="temperature"></p>
            <p id="description"></p>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>



Enter fullscreen mode Exit fullscreen mode

Step 3: Style Your App

Create a CSS file (e.g., styles.css) to style your weather app. Here's a basic CSS code example:



body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

.container {
    max-width: 400px;
    margin: 0 auto;
    text-align: center;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.5); /* Set the background color to be transparent */
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); /* Adjust the alpha value here for the box shadow transparency */
    margin-top: 105px;
}

h1 {
    font-size: 24px;
}

input[type="text"] {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    background-color: #007BFF;
    color: #fff;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
}

.weather-info {
    margin-top: 20px;
}

/* Add more styles as needed */



Enter fullscreen mode Exit fullscreen mode

Step 4: Fetch Weather Data with JavaScript

Create a JavaScript file (e.g., script.js) to fetch weather data from a public weather API. We'll use the OpenWeatherMapAPI as an example. You'll need to sign up for a free API key from OpenWeatherMap.



const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://api.openweathermap.org/data/2.5/weather';

const locationInput = document.getElementById('locationInput');
const searchButton = document.getElementById('searchButton');
const locationElement = document.getElementById('location');
const temperatureElement = document.getElementById('temperature');
const descriptionElement = document.getElementById('description');

searchButton.addEventListener('click', () => {
    const location = locationInput.value;
    if (location) {
        fetchWeather(location);
    }
});

function fetchWeather(location) {
    const url = `${apiUrl}?q=${location}&appid=${apiKey}&units=metric`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            locationElement.textContent = data.name;
            temperatureElement.textContent = `${Math.round(data.main.temp)}°C`;
            descriptionElement.textContent = data.weather[0].description;
        })
        .catch(error => {
            console.error('Error fetching weather data:', error);
        });
}



Enter fullscreen mode Exit fullscreen mode

Step 5: Get Your API Key

Sign up for a free API key from OpenWeatherMap (or another weather API provider of your choice). Replace 'YOUR_API_KEY' in the JavaScript code with your actual API key.

weatherapp API KEY

weatherappAPIkey

Step 6: Test Your Weather App

Open your HTML file (index.html) in a web browser, enter a city name, and click the "Search" button. You should see the weather information displayed on the page.

weathermap code base

weatherapp

I've added the background picture to the body element in the CSS style to beautify the weather app. Here's the updated code snippet with the background image included:



body {
  font-family: Arial, sans-serif;
    /* background-color: #f0f0f0; */

  background-image: url('weather1.webp');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh; /* Set the height to fill the viewport */
  margin: 0; /* Remove default margin */
  padding: 0; 
}


Enter fullscreen mode Exit fullscreen mode

Step 7: Deploy Your Weather App

To share your weather app with others, you can deploy it on a web hosting platform or use a service like GitHub Pages.

This is a basic example of a weather app. You can further enhance it by adding features like icons, more detailed weather information, and a five-day forecast. You can also improve the styling to make it more visually appealing.

LinkedIn Account : LinkedIn
Twitter Account: Twitter
Credit: Graphics sourced from Hackr.io

Top comments (18)

Collapse
 
mahfuzurrahman01 profile image
Mafuzur Rahman • Edited

this is my weather app UI
Recently I've also done this weather app for Fun.
here it is you can also check out this one.

Live link

I've used Nextjs, Typescript, and Axios.

Collapse
 
iamcymentho profile image
Odumosu Matthew

That sounds awesome! Weather apps are a great project to work on. I'd love to check out your version. Thanks for sharing the the live link . Could you share the GitHub repository link so I can take a look?

Collapse
 
mahfuzurrahman01 profile image
Mafuzur Rahman

Sure here is the GitHub link: github.com/mahfuzurrahman01/weathe...

Collapse
 
punith_k_e9a79d929e7699be profile image
Punith K

Need complete code

Collapse
 
pragnya_parimitanath_f14 profile image
Pragnya parimita nath

send the source code

Collapse
 
mkstancreative profile image
Chidimma Stanley

Nice, I will try to build it using react

Collapse
 
iamcymentho profile image
Odumosu Matthew

Absolutely, using React can indeed lead to a more efficient and maintainable application. It provides a structured way to manage your app's state and UI components. I

Collapse
 
olivia73code profile image
Olivia73-code

Thank you so much for sharing, I am on the CSS leg of my learning journey but I'm excited to try this app out locally in the future. This was easy to follow thank you.

Collapse
 
tarun2804 profile image
Tarun2804

it doesnot showing anything

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="Container">
        <h1>Weather App</h1>
        <input type="text" id="locationInput" placeholder="Enter city name">
        <button id="searchButton">Search</button>
        <div class="weather-info">
            <h2>Location</h2>
            <p>Temperature</p>
            <p>Description</p>
        </div>

    </div>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

body {
font-family: 'Courier New', Courier, monospace;
background-color: aqua;
}

.Container {
max-width: 400px;
margin: 0 auto;
text-align: center;
padding: 20px;
background-color: rgba(255, 255, 255, 0.5);
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
margin-top: 105px;
}
h1 {
font-size: 25px;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
background-color: #007BFF;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
.weather-info {
margin-top: 20px;
}

`

`
const apiKey = "6d7fa8bbc9d11323a4360290364f544d";
const apiUrl = "api.openweathermap.org/data/2.5/we...";

const locationInput = document.getElementById('locationInput');
const searchButton = document.getElementById('searchButton');
const locationElement = document.getElementById('location');
const temperatureElement = document.getElementById('temperature');
const descriptionElement = document.getElementById('description');

searchButton.addEventListener('click', () => {
const location = locationInput.value;
if (location) {
fetchWeather(location);
}
});

function fetchWeather(location) {
const url = ${apiUrl}?q=${location}&appid=${apiKey}&units=metric;

fetch(url)
    .then(response => response.json())
    .then(data => {
        locationElement.textContent = data.name;
        temperatureElement.textContent = `${Math.round(data.main.temp)}°C`;
        descriptionElement.textContent = data.weather[0].description;
    })
    .catch(error => {
        console.error('Error fetching weather data:', error);
    });
Enter fullscreen mode Exit fullscreen mode

}
`
`


Enter fullscreen mode Exit fullscreen mode
Collapse
 
dumebii profile image
Dumebi Okolo

Amazing!
But a screenshot of the finished work, or a link to it would be great.

Collapse
 
iamcymentho profile image
Odumosu Matthew

Thank you for the tip.I have now attached a screenshot of the finished work.

Collapse
 
dumebii profile image
Dumebi Okolo

Awesome.

Collapse
 
rolandixor profile image
Roland Taylor

Great tutorial!

Like Dumebi, I would suggest including a screenshot or a codepen or similiar. You can even link to the code on Github/Gitlab/Gumroad, if you like!

Collapse
 
iamcymentho profile image
Odumosu Matthew

Thank you for the feedback! I'm glad you found the tutorial helpful. I've attached some screenshots, and I'll be sure to add the GitHub link before the day is over. Stay tuned for the link, and feel free to reach out if you have any questions or need further assistance.

Collapse
 
jangelodev profile image
João Angelo

Hi Odumosu Matthew,
Top, very nice!
Thanks for sharing.

Collapse
 
iamcymentho profile image
Odumosu Matthew

Thank you so much for your kind words! I'm glad you found the guide helpful. If you have any questions or need further insights, feel free to reach out!

Collapse
 
madhumitha_m_f6551cc909d5 profile image
MADHUMITHA M

I want want the full source code sir...anyone pls help me....

Collapse
 
collinzo2022 profile image
Efuetanu Collins

Thanks for this it was quite informative, looking forward to documenting my journey for recruiters. Currently jobless any tips