JavaScript Weather App Development Tutorial For Beginners

Are you new to JavaScript programming and eager to develop your own weather application? Look no further! In this comprehensive tutorial, the author will guide you step-by-step in creating a dynamic and simple weather app using JavaScript. Weather applications have become an essential part of our daily lives, providing us with up to date weather forecasts and real time conditions. With the sophistication and power of JavaScript, you can create a weather app that fetches data from weather APIs and presents it in a visually appealing manner.

Weather App

A weather app or weather application in JavaScript is a computer program used to provide information about the weather at a specific location. This app can be accessed through a web browser or mobile application and is usually supported by weather APIs, which provide data about temperature, humidity, air pressure, wind speed, and other weather conditions. In creating a weather app using JavaScript, the author needs to fetch weather data from an API and present that information in a user-friendly manner.

Weather apps created with JavaScript typically have interactive and engaging user interfaces, allowing users to select locations and customize their preferences. Some common features found in weather apps include short-term and long-term weather forecasts, current weather condition information, and interactive weather radars. Some weather apps even display graphs and tables to help users understand weather changes over time.

Creating a weather app in JavaScript involves several technologies, including HTML, CSS, and JavaScript. Authors must use HTML to build the app's layout, CSS to design the appearance and style, and JavaScript to program the app's behavior. One of the main challenges in creating a weather app is ensuring that the weather data received from the API is accurate and up-to-date. Therefore, authors need to update the data regularly and take action if there are errors or failures in the API connection.

Weather apps in JavaScript can provide significant benefits to users, especially in terms of travel planning or outdoor activities. With the app, users can quickly and easily check the weather conditions at a specific location and adjust their plans according to the weather forecast. Additionally, weather apps can also help users understand and monitor weather changes over time, enabling them to make better decisions in their daily lives.

Overall, a weather app in JavaScript is a useful and effective tool for obtaining weather information at a specific location. With its interactive features and appealing interface, the app can help users comprehend weather conditions and make informed decisions. Therefore, creating a weather app using JavaScript is an engaging and beneficial project for both app developers and users.

OpenWeatherMap Registration

Before we start the tutorial, the author will use the OpenWeatherMap API. You need to register first to obtain an API key. Here are the steps to register on OpenWeatherMap and get an API key:

  1. Open the OpenWeatherMap website at https://home.openweathermap.org/users/sign_up to register.
  2. Enter your email address and password.
  3. After that, you will be asked to verify your email address.
  4. After verification, you can log in to your account on OpenWeatherMap.
  5. To obtain the API key on the OpenWeatherMap website, click on the profile name in the navbar, then select the "My API Keys" option from the dropdown menu.
  6. On your profile page, you can view your API key.
  7. You can use this API key to fetch weather data from the OpenWeatherMap API in your application and follow this tutorial. Don't forget to check the OpenWeatherMap API documentation to learn how to use the available API endpoints. Here is the link to the OpenWeatherMap API documentation https://openweathermap.org/api.

Tutorial

  1. First, create a folder named weather-app-js.
  2. Open your IDE.
  3. Create an HTML file named index.html and save into weather-app-js folder.
  4. Here is the code :
  5. <html>
    <head>
        <title>Weather App</title> <!-- Weather App title -->
        <link rel="stylesheet" href="style.css"> <!-- Importing external CSS file -->
    </head>
        
    <body>
        
        <div class="weather-container">
            
            <input type="text" placeholder="Enter city or postal code" id="input-field"> <!-- Input field for city or postal code -->
            <button type="button">Search</button> <!-- Search button -->
            
          <div class="weather-info">
            <div id="city"></div> <!-- Element to display city name -->
            <div id="icon"></div> <!-- Element to display weather icon -->
            <div id="temperature"></div> <!-- Element to display temperature -->
            <div id="description"></div> <!-- Element to display weather description -->
          </div>
        </div> 
        
        <script src="script.js"></script> <!-- Importing external JavaScript file -->
    </body>
    </html>

  6. Then, create style.css for CSS and save into weather-app-js folder.
  7. /* CSS code to center the elements and apply a bright blue background */
    
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      background-color: #00a8e8; /* Bright blue background color */
    }
    
    .weather-container {
      text-align: center;
      padding: 20px;
      border-radius: 10px;
      background-color: #ffffff; /* White background color for weather container */
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    
    #input-field {
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      margin-bottom: 10px;
    }
    
    button {
      padding: 10px 20px;
      background-color: #4caf50;
      color: #ffffff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    
    .weather-info {
      margin-top: 20px;
    }
    
    #city,
    #icon,
    #temperature,
    #description {
      font-size: 18px;
      margin-bottom: 10px;
    }
    
    #icon {
      font-size: 50px;
    }

  8. UI for weather app when you open the index.html file in weather-app-js folder :
  9. Now, create script.js for javascript file and save into weather-app-js folder.
  10. Here is the code :
  11. let inputField = document.querySelector('#input-field');
    let btn = document.querySelector('button');
    let city = document.querySelector('#city');
    let icon = document.querySelector('#icon');
    let temperature = document.querySelector('#temperature');
    let description = document.querySelector('#description');
    
    btn.addEventListener('click', function(){
    
      const url = `https://api.openweathermap.org/data/2.5/weather?q=${inputField.value}&appid=YOUR_API_KEY`;
      
      fetch(url)
        .then(response => response.json())
        .then(data => {
          city.innerText = data.name;
          icon.innerHTML = `<img src="https://openweathermap.org/img/w/${data.weather[0].icon}.png" alt="icon">`;
          temperature.innerText = `${Math.round(data.main.temp)}°C`;
          description.innerText = data.weather[0].description;
        })
        .catch(error => console.log('Error:', error));
    });

    Here's a step-by-step explanation of the JavaScript code provided :

    Initialize variables:
    let inputField = document.querySelector('#input-field');
    let btn = document.querySelector('button');
    let city = document.querySelector('#city');
    let icon = document.querySelector('#icon');
    let temperature = document.querySelector('#temperature');
    let description = document.querySelector('#description');

    - The inputField variable holds the element with the id "input-field," which is assumed to be an input field where the user enters the city name.

    - The btn variable holds the first button element found in the document.

    - The city, icon, temperature, and description variables hold elements with the ids "city," "icon," "temperature," and "description," respectively. These elements will be used to display weather information.

    Event listener for the button:
    btn.addEventListener('click', function(){
      // ...
    });

    - When the button is clicked, the callback function will be executed to make a weather data request to the OpenWeatherMap API.

    Forming the API URL:
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${inputField.value}&appid=YOUR_API_KEY`;

    - In this URL, inputField.value will take the value entered by the user into the input field.

    - YOUR_API_KEY should be replaced with a valid OpenWeatherMap API key.

    Using fetch to call the API:
    fetch(url)
      .then(response => response.json())
      .then(data => {
        // ...
      })
      .catch(error => console.log('Error:', error));

    - fetch() is a built-in JavaScript function used to fetch data from external sources, in this case, the OpenWeatherMap API.

    - .then() This is a method that is called on a Promise object. It takes a callback function as an argument, which will be executed when the Promise is fulfilled or resolved successfully.

    - response.json() will convert the response data into JSON format that can be used. When the fetch request is successful and the server returns a response, the .then() method with response => response.json() will be executed. It reads the response and parses it as JSON data, and the Promise will resolve with the JavaScript object representing the JSON data. This makes it easy to work with the response data in a structured and convenient manner.

    - data => { ... } This is the callback function passed to the .then() method. The data parameter represents the resolved value of the Promise, which, in this case, is the Response object returned by the fetch() function after a successful network request.

    - .catch(error => console.log('Error:', error)); If an error occurs during the weather data request, the error message will be printed to the console.

    Displaying weather data into HTML elements:
    city.innerText = data.name;
    icon.innerHTML = `<img src="https://openweathermap.org/img/w/${data.weather[0].icon}.png" alt="icon">`;
    temperature.innerText = `${Math.round(data.main.temp)}°C`;
    description.innerText = data.weather[0].description;

    - data.name is the city name obtained from the API response and will be displayed in the element with the id "city."

    - data.weather[0].icon is the weather icon code from the API response. This code will be used to form the URL of the weather icon image, which will be displayed in the element with the id "icon."

    - data.main.temp is the temperature in Kelvin format obtained from the API response. This temperature will be converted to Celsius and displayed in the element with the id "temperature."

    - data.weather[0].description is the weather description from the API response and will be displayed in the element with the id "description."

  12. The result when the author enters the city name 'Tegal' from indonesia :
  13. Done.

Closing

In this article, we have learned how to create a simple weather application using the JavaScript programming language and leveraging the API from OpenWeatherMap. I hope you like it!