Interactive JavaScript Weather App for Accurate Forecasts | electro4u

17 Dec 2021 Balmiki Mandal 0 JavaScript

Weather App in JavaScript

Overview

This tutorial will show you how to build a weather app in JavaScript using the OpenWeatherMap API. This API allows you to get real-time weather data for any location in the world.

Prerequisites

  • Basic knowledge of HTML and CSS
  • Basic knowledge of JavaScript

Steps 01: Create a new HTML file and add the following code:

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Weather App</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Weather App</h1>
  <input type="text" id="city-input" placeholder="Enter a city name">
  <button type="button" id="search-button">Search</button>
  <div id="weather-info"></div>

  <script src="script.js"></script>
</body>
</html>

Syteps 02: Create a new CSS file and add the following code:

CSS
body {
  font-family: sans-serif;
}

h1 {
  text-align: center;
}

input {
  width: 200px;
  margin: 0 10px;
}

button {
  margin: 0 10px;
}

#weather-info {
  margin-top: 20px;
}

Steps 03: Create a new JavaScript file and add the following code:

JavaScript
const apiKey = "YOUR_API_KEY";

const cityInput = document.querySelector("#city-input");
const searchButton = document.querySelector("#search-button");
const weatherInfo = document.querySelector("#weather-info");

searchButton.addEventListener("click", async () => {
  const city = cityInput.value;

  const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`);
  const data = await response.json();

  const temperature = data.main.temp;
  const condition = data.weather[0].main;

  weatherInfo.innerHTML = `
    <h3>${city}</h3>
    <p>Temperature: ${temperature}°C</p>
    <p>Condition: ${condition}</p>
  `;
});

Steps 04: Replace YOUR_API_KEY with your own OpenWeatherMap API key.

Steps 05: Save all of your files and open the HTML file in a web browser.

Steps 06: Enter a city name in the input field and click the "Search" button.

The weather information for the city will be displayed in the "Weather Info" section below the search bar.

Conclusion

This is a basic example of a weather app in JavaScript. You can extend this app to add more features, such as a forecast, a search history, and support for different units of measurement.

Top Resources Now:


Enroll Now:


[JavaScript 2023-2024: From Scratch to Advanced] "Start Supercharging Your Productivity!"

Contact Us:


  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.