Creating A Weather Search App in Vanilla JavaScript

Creating A Weather Search App in Vanilla JavaScript

How I made a weather app as part of my first project in a Software Engineering Bootcamp

This post covers creating a simple weather search application using plain JavaScript, HTML, and CSS.

Demo and Source Code

The project demo is live on codesandbox, and the source code is available on GitHub.

Prerequisites

  1. Openweathermap API Keys
  2. JavaScript Fetch API and DOM Manipulation
  3. Basic HTML and CSS

Creating the HTML and CSS Files

Create a new file (index.html) and add the following:

<!DOCTYPE html>
<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" />
    <title>Weather Robot</title>
    <link rel="stylesheet" href="./weatherRobot.css" />
  </head>
  <body>
    <section class="section-head">
      <div class="container">
        <h1 class="heading">Weather Robot</h1>
        <form>
          <input type="text" placeholder="Search for a city" autofocus />
          <button type="submit">GET WEATHER</button>
          <span class="msg"></span>
        </form>
      </div>
    </section>
    <section class="city-array">
      <div class="container">
        <ul class="cities"></ul>
      </div>
    </section>
    <script src="./weatherRobot.js"></script>
  </body>
</html>

Create separate files for the styles and JavaScript. Inside the CSS file, add the following:

Open the file on your browser to view the web page

image.png

Now let's add some functionality to search and get weather information!

Getting OpenWeatherMap API Keys:

After signing in to your account, navigate to home.openweathermap.org/api_keys to get your API Keys:

image.png

Inside the js file, add the following at the top:

const form = document.querySelector('.section-head form'),
  input = document.querySelector('.section-head input'),
  msg = document.querySelector('.section-head .msg'),
  list = document.querySelector('.city-array .cities'),
  apiKey = 'API_KEY'

Replace the API_KEY with your API Key from OpenWeatherMap.

In the snippets above, we grab the input to capture the city name entered by a user, document.querySelector('.section-head input'), and return the results in a list list = document.querySelector('.city-array .cities'),

We then create an event listener to listen for user inputs and query the API to get the weather of the entered city:

form.addEventListener('submit', (e) => {

}

Copy the following code inside the event listener function:

Run the file to view the changes. For every valid city searched, it's added on the card list:

image.png