DEV Community

Cover image for Project: Build a Weather App Using JavaScript and a Weather API
arjun
arjun

Posted on

Project: Build a Weather App Using JavaScript and a Weather API

Project: Build a Weather App Using JavaScript and a Weather API

Date: December 18, 2024

Building a weather app is an excellent way to solidify your understanding of JavaScript, DOM manipulation, event handling, and API integration. This project will teach you how to fetch data from an API and display it dynamically on a webpage.


Project Overview

Features of the Weather App

  1. Fetch real-time weather data from a weather API (e.g., OpenWeatherMap).
  2. Input functionality: Users can search for weather details by entering a city name.
  3. Dynamic UI updates: Display temperature, humidity, and weather conditions dynamically.
  4. Error handling for invalid city names or API issues.

Step-by-Step Guide

1. Set Up Your Project

Create the necessary files for your project:

  • HTML: Structure the layout.
  • CSS: Style the app (optional for basic functionality).
  • JavaScript: Add interactivity and integrate the weather API.

2. Get a Weather API Key

Sign up at OpenWeatherMap and get an API key. You’ll use their API to fetch weather data.

Example API URL:

https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric
Enter fullscreen mode Exit fullscreen mode

3. Basic HTML Structure

Create a simple layout with an input field and a section to display weather information.

<!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 id="weather-app">
    <h1>Weather App</h1>
    <input type="text" id="city-input" placeholder="Enter city name">
    <button id="search-btn">Search</button>
    <div id="weather-result">
      <p id="error-message"></p>
      <h2 id="city-name"></h2>
      <p id="temperature"></p>
      <p id="description"></p>
      <p id="humidity"></p>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

4. Styling (Optional)

Add some CSS to make your app visually appealing.

#weather-app {
  text-align: center;
  font-family: Arial, sans-serif;
  margin: 50px auto;
  width: 300px;
}

input, button {
  padding: 10px;
  margin: 10px 0;
}

#weather-result {
  margin-top: 20px;
}
Enter fullscreen mode Exit fullscreen mode

5. Writing the JavaScript Code

DOM Manipulation and Event Handling

Use JavaScript to capture the user input, fetch data from the API, and display the results.

// JavaScript code for the weather app
const API_KEY = "your_api_key_here"; // Replace with your actual API key

document.getElementById("search-btn").addEventListener("click", () => {
  const city = document.getElementById("city-input").value;
  if (city) {
    fetchWeather(city);
  } else {
    displayError("Please enter a city name.");
  }
});

function fetchWeather(city) {
  const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

  fetch(apiURL)
    .then(response => {
      if (!response.ok) {
        throw new Error("City not found");
      }
      return response.json();
    })
    .then(data => displayWeather(data))
    .catch(error => displayError(error.message));
}

function displayWeather(data) {
  document.getElementById("error-message").textContent = "";
  document.getElementById("city-name").textContent = `Weather in ${data.name}`;
  document.getElementById("temperature").textContent = `Temperature: ${data.main.temp}°C`;
  document.getElementById("description").textContent = `Condition: ${data.weather[0].description}`;
  document.getElementById("humidity").textContent = `Humidity: ${data.main.humidity}%`;
}

function displayError(message) {
  document.getElementById("error-message").textContent = message;
  document.getElementById("city-name").textContent = "";
  document.getElementById("temperature").textContent = "";
  document.getElementById("description").textContent = "";
  document.getElementById("humidity").textContent = "";
}
Enter fullscreen mode Exit fullscreen mode

6. Testing the App

  1. Open the HTML file in a browser.
  2. Enter a city name (e.g., “London”) and click "Search".
  3. Verify that the weather details appear on the page.
  4. Test for invalid cities and empty input to ensure error messages display correctly.

Web Wheather app

My GitHub Repo here click

7. Features to Add Later (Optional Enhancements)

  1. Geolocation: Automatically detect the user's location and display the weather.
  2. Weather Icons: Use weather icons from the API response.
  3. Styling: Add animations or a responsive design for mobile users.
  4. Forecast: Show a 5-day weather forecast.

Project Summary

Building a weather app integrates many important JavaScript skills, such as:

  • Fetching and handling API data.
  • Dynamically manipulating the DOM.
  • Handling user input and displaying results interactively.

By completing this project, you’ll gain confidence in building more complex JavaScript applications.


Next Steps: Tomorrow, we’ll focus on Error Handling and Debugging in JavaScript, exploring techniques to identify and resolve issues effectively. Stay tuned!

Top comments (0)