"CONTACT US FOR WEB/ADS"

How to Build a Simple Weather App with JavaScript and OpenWeather API



Introduction


How to Build a Simple Weather App with JavaScript and OpenWeather API



Building projects is the fastest way to improve your coding skills. In this tutorial, we’ll create a simple Weather App using HTML, CSS, and JavaScript with the OpenWeather API. By the end, you’ll understand how to fetch data from an external API and display it on a webpage.

Prerequisites

Before you begin, make sure you have:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A code editor (e.g., VS Code).
  • A web browser.
  • A free OpenWeather API key.


Step 1: Setup the Project Folder

Create a new folder named weather-app and add three files:

index.html

style.css

script.js


Step 2: HTML Structure

<!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="style.css">
</head>
<body>
  <div class="app">
    <h1>Weather App</h1>
    <input type="text" id="city" placeholder="Enter city name">
    <button onclick="getWeather()">Check Weather</button>
    <div id="result"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Step 3: Basic Styling (CSS)

body {
  font-family: Arial, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f2f2f2;
}

.app {
  text-align: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

Step 4: JavaScript Logic

async function getWeather() {
  const city = document.getElementById("city").value;
  const apiKey = "YOUR_API_KEY_HERE";
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  const response = await fetch(url);
  const data = await response.json();

  if (data.cod === 200) {
    document.getElementById("result").innerHTML =
      `<h2>${data.name}, ${data.sys.country}</h2>
       <p>Temperature: ${data.main.temp} °C</p>
       <p>Weather: ${data.weather[0].description}</p>`;
  } else {
    document.getElementById("result").innerHTML = `<p>City not found!</p>`;
  }
}

Step 5: Test the App

1. Replace "YOUR_API_KEY_HERE" with your actual OpenWeather API key.


2. Open index.html in your browser.


3. Enter a city name and check the weather!



Conclusion

You’ve just built a simple Weather App with JavaScript. This project introduced you to fetching data from APIs and dynamically updating the DOM. 


Happy coding! 

0 Comments


Are you an Artiste? Do you want your music to go viral and reach a large number of Audience? Promote your music on LITEUP9JA by clicking HERE. You can also advertise your product or brand by clicking HERE.