Learn to build a weather app in just 5 mins
Tags: webdev, javascript, beginners, programming
Published: 2022-11-13 23:53:28

A tutorial on how you can build a customizable weather app just using HTML, CSS, and JavaScript.

## Intro
Every single day we check the weather forcast before going to work and when I was a kid I used to think about how can I build my own weather app so that I can add customizations, more specific weather details , and a nice background of my choice, and today I have made my own weather app using JavaScript just with a few lines of code.
In this article, I will demonstrate how you can build your own JavaScript weather app just using HTML, CSS, and JavaScript and I can guarantee you can also customize it on your own.

## Getting started
Building this web app you will learn some core JavaScript and dom manipulation concepts like event listener, fetch api, classes , query selector, etc. Don’t worry if you are new to JavaScript I will explain every single topic concisely with proper demos. So let’s jump onto building an amazing micro project.

## Building the structure
We all know that building a website consists of three blocks of HTML for the structure, which contains all the key elements that will be present in our webpage like the images, paragraphs, headings, etc. As you can imagine a weather will contain some keys or buttons a placeholder to put some details and a few details.So quilcky create an `index.html` file and add the code.
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>The Weather App</title>
    <link rel="shortcut icon" href="https://img.icons8.com/external-inipagistudio-mixed-inipagistudio/64/000000/external-weather-app-weather-forecast-inipagistudio-mixed-inipagistudio.png" type="image/x-icon">
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="./style.css" />
    <script src="./script.js" defer></script>
  </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 1024 1024"
            height="1.5em"
            width="1.5em"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"
            ></path>
          </svg>
        </button>
      </div>
      <div class="weather loading">
        <h2 class="city">Weather in Kolkata</h2>
        <h1 class="temp">21°C</h1>
        <div class="flex">
          <img src="https://img.icons8.com/ios/20/000000/snow-storm--v1.png" />
          <h4 class="feels_like">18°C</h4>
        </div>

        <div class="flex">
          <img
            src="https://openweathermap.org/img/wn/04n.png"
            alt=""
            class="icon"
          />
          <div class="description">Cloudy</div>
        </div>
        <div class="humidity">Humidity: 10%</div>
        <div class="wind">Wind speed: 6.2 km/h</div>
      </div>
    </div>
  </body>
</html>
``` 

![Html](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0gu43krhug715q0unsf.png)

This is how our app looks like with basic `HTML` code and some dummy data.

## Adding the styles 
In order to make our app look cool let's add some style to it. 
so quickly create a style.css file and add the code below.
```css
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    font-family: 'Roboto', sans-serif;
    background: #222;
    background-image: url('https://source.unsplash.com/1600x900/?landscape');
    font-size: 120%;
  }
  
  .card {
    background: #b6a7a7d0;
    color: rgb(10, 7, 7);
    padding: 1.5rem;
    border-radius: 10px;
    width: 100%;
    max-width: 420px;
    margin: 1em;
  }
  
  .search {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  button {
    margin: 0.5rem;
    border-radius: 50%;
    border: none;
    height: 44px;
    width: 44px;
    outline: none;
    background: #7c7c7c2b;
    color: white;
    cursor: pointer;
    transition: 0.2s ease-in-out;
  }
  
  input.search-bar {
    border: none;
    outline: none;
    padding: 0.4em 1em;
    border-radius: 24px;
    background: #7c7c7c2b;
    color: white;
    font-family: inherit;
    font-size: 105%;
    width: calc(100% - 100px);
  }
  
  button:hover {
    background: #7c7c7c6b;
  }
  
  h1.temp {
    margin: 0;
    margin-bottom: 0.4em;
  }
  
  .flex {
    display: flex;
    align-items: center;
  }
  
  .description {
    text-transform: capitalize;
    margin-left: 8px;
  }
  
  .weather.loading {
    visibility: hidden;
    max-height: 20px;
    position: relative;
  }
  
  .weather.loading:after {
    visibility: visible;
    content: "Loading...";
    color: white;
    position: absolute;
    top: 0;
    left: 20px;
  }
```
 

![weather app with styles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2idxrnd2yz67hd6p3zq.png)

Now this is how our app looks with some styles. Here I am using the  `unsplash` API in order to get a different background image every  time we refresh the page.

## Let's add the freatures
Till now we our app is running with dummy data which means you can't get the weather details of a particular city.So now we will b e using JavaScirpt to add some cool features to our app. Make sure you visit [openweathermap](https://openweathermap.org/) and Grab your API keys. Now quickly create a script.js file and add the code below to see the magic.

```javascript
let weather = {
  //the api key
  apiKey: "YOUR_API_KEY",
  //fetching the weather form the api 
  fetchWeather: function (city) {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
      city +
      "&units=metric&appid=" +
      this.apiKey
    )
      .then((response) => {
        if (!response.ok) {
          alert("No weather found.");
          throw new Error("No weather found.");
        }
        return response.json();
      })
      .then((data) => this.displayWeather(data));
  },
  //function for displaying weather 
  displayWeather: function (data) {
    const { name} = data;
    const { icon, description } = data.weather[0];
    const { temp, humidity, feels_like } = data.main;
    const { speed } = data.wind;
    document.querySelector(".city").innerText = "Weather in " + name;
    document.querySelector(".icon").src =
      "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = temp + "°C";
    document.querySelector(".feels_like").innerText = " "+ feels_like + "°C";
    document.querySelector(".humidity").innerText =
      "Humidity: " + humidity + "%";
    document.querySelector(".wind").innerText =
      "Wind speed: " + speed + " km/h";
    document.querySelector(".weather").classList.remove("loading");
    document.body.style.backgroundImage =
      "url('https://source.unsplash.com/1600x900/?" + name + "')";
  },
  //searching weather 
  search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
  },
};

document.querySelector(".search button").addEventListener("click", function () {
  weather.search();
});

document
  .querySelector(".search-bar")
  .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
      weather.search();
    }
  });
//default weather
weather.fetchWeather("Kolkata");
//this app is designed and developed by Kumar Kalyan

```
So all I'm doing here is that I have created an object named weather which contains some functions. In the begining I am taking the city name form the user using the `evetlistners` and then passing it to the `fetchWeather()` which returns the weather data of the given city and finally using javascript we are dynamically changing the data in `HTML` using classes and `querySelector ` property.

##Important tips 
- Makesure you hide your API Keys from others 
- Try to write less amount to code using objects 
- Use proper comments  and variable names 

##Conclusion
Congratulations! You just learned to create your own weather app using JavaScript. Feel free to add customizations, style, and more features while you make your own. Stay tuned for the next. 
Happy Coding :)