Open In App

Build A Weather App in HTML CSS & JavaScript

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A weather app contains a user input field for the user, which takes the input of the city name. Once the user enters the city name and clicks on the button, then the API Request is been sent to the OpenWeatherMap and the response is been retrieved in the application which consists of weather, wind speed, description, etc.

Preview Image

Screenshot-2024-02-09-at-14-16-59-GFG-App

Project Overview

Our weather app will have the following features:

  • City Name Input: Users can enter a city name.
  • Weather Data Fetching: The app fetches weather data from the OpenWeatherMap API.
  • Display Weather Information: Shows temperature, wind speed, weather description, etc.
  • Error Handling: If an invalid city is entered, the app will show an error message.
  • Default Weather: By default, it will show the weather for Pune.

Step 1: Setting Up the Project

Create a directory for your project and create three files inside it:

  • index.html – The HTML file for the structure of the app.
  • styles.css – The CSS file for styling the app.
  • script.js – The JavaScript file for fetching the weather data and adding interactivity.

Step 2: HTML Structure

This is the structure of the weather app. We will use basic HTML elements like <div>, <input>, and <button> to create the input field, button, and display the weather data.

<!DOCTYPE html>
<head>
	<link rel="stylesheet" href="style2.css">
	<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
	<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
	<link rel="stylesheet" href=
"https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap">
	<title>GFG App</title>
</head>

<body>
	<div class="container">
		<div class="weather-card">
			<h1 style="color: green;">
				GeeksforGeeks
			</h1>
			<h3>
				Weather App
			</h3>
			<input type="text" id="city-input"
				placeholder="Enter city name">
			<button id="city-input-btn"
					onclick="weatherFn($('#city-input').val())">
					Get Weather
			</button>
			<div id="weather-info"
				class="animate__animated animate__fadeIn">
				<h3 id="city-name"></h3>
				<p id="date"></p>
				<img id="weather-icon" src="" alt="Weather Icon">
				<p id="temperature"></p>
				<p id="description"></p>
				<p id="wind-speed"></p>
			</div>
		</div>
	</div>
	<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
	</script>
	<script src=
"https://momentjs.com/downloads/moment.min.js">
	</script>
	<script src="script2.js"></script>
</body>
</html>

In this Example:

  • <input>: This input field allows the user to type in the city name.
  • <button>: When clicked, this button will trigger the weather fetching logic.
  • #weather-info: A container that holds the weather details, such as temperature, description, and wind speed. Initially hidden.
  • #error-message: This element displays an error message when the city is invalid or not found. It is also hidden initially.

Step 3: Styling with CSS

Next, add some basic styling to make the Weather app visually appealing. Open the styles.css file and add the following CSS code:

body {
    margin: 0;
    font-family: 'Montserrat', sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: linear-gradient(to right, #4CAF50, #2196F3);
}

.container {
    text-align: center;
}

.weather-card {
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease-in-out;
    width: 450px;
}

.weather-card:hover {
    transform: scale(1.05);
}

#city-input {
    padding: 15px;
    margin: 10px 0;
    width: 70%;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
}

#city-input:focus {
    outline: none;
    border-color: #2196F3;
}

#city-input::placeholder {
    color: #aaa;
}

#city-input-btn {
    padding: 10px;
    background-color: #2196F3;
    color: #fff;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
}

#city-input-btn:hover {
    background-color: #1565C0;
}

#weather-info {
    display: none;
}

#weather-icon {
    width: 100px;
    height: 100px;
}

#temperature {
    font-size: 24px;
    font-weight: bold;
    margin: 8px 0;
}

#description {
    font-size: 18px;
    margin-bottom: 10px;
}

#wind-speed {
    font-size: 16px;
    color: rgb(255, 0, 0);
}

#date {
    font-size: 14px;
    color: rgb(255, 0, 0);
}

In this Example:

  • The page is centered using Flexbox with a smooth gradient background that transitions from green to blue.
  • The weather details are in a card with a semi-transparent white background, rounded corners, and a shadow. It slightly enlarges when hovered.
  • The input field allows users to type the city name, with padding, a light border, and a blue border when focused, plus gray placeholder text.
  • The button triggers the weather-fetching action, has a blue background, white text, rounded corners, and changes to a darker blue on hover.
  • Weather details are initially hidden. When shown, they include a 100px weather icon, bold and larger temperature, medium-sized description, and red wind speed and date for emphasis.

Step 4: Add JavaScript

In this step, we'll implement the logic that interacts with the OpenWeatherMap API to fetch weather data and display it to the user.

const url =
	'https://api.openweathermap.org/data/2.5/weather';
const apiKey =
	'f00c38e0279b7bc85480c3fe775d518c';

$(document).ready(function () {
	weatherFn('Pune');
});

async function weatherFn(cName) {
	const temp =
		`${url}?q=${cName}&appid=${apiKey}&units=metric`;
	try {
		const res = await fetch(temp);
		const data = await res.json();
		if (res.ok) {
			weatherShowFn(data);
		} else {
			alert('City not found. Please try again.');
		}
	} catch (error) {
		console.error('Error fetching weather data:', error);
	}
}

function weatherShowFn(data) {
	$('#city-name').text(data.name);
	$('#date').text(moment().
		format('MMMM Do YYYY, h:mm:ss a'));
	$('#temperature').
		html(`${data.main.temp}°C`);
	$('#description').
		text(data.weather[0].description);
	$('#wind-speed').
		html(`Wind Speed: ${data.wind.speed} m/s`);
	$('#weather-icon').
		attr('src',
			`...`);
	$('#weather-info').fadeIn();
}

In this Example:

  • The url and apiKey variables store the API endpoint and key to access the weather data from OpenWeatherMap.
  • The weatherFn function sends a request to the OpenWeatherMap API with the city name (default is "Pune") and retrieves the weather data asynchronously. If the request is successful, it proceeds to display the data.
  • If the city is not found or an error occurs, an alert is shown to the user saying "City not found. Please try again."
  • The weatherShowFn function updates the webpage with weather details such as the city name, temperature, description, wind speed, and current date/time. It also sets the weather icon (though the icon URL is missing and needs to be added).
  • The current date and time are displayed using moment.js, formatted as "Month day, year, time" (e.g., "April 16th 2025, 3:45:00 PM").

Weather App - Complete Code

Example: This example describes the basic implementation for a Weather App in HTML CSS and JavaScript,

HTML
<!DOCTYPE html>

<head>
	<link rel="stylesheet" href="style.css">
	<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
	<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
	<link rel="stylesheet" href=
"https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap">
	<title>GFG App</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
	<div class="container">
		<div class="weather-card">
			<h1 style="color: green;">
				GeeksforGeeks
			</h1>
			<h3>
				Weather App
			</h3>
			<input type="text" id="city-input"
				placeholder="Enter city name">
			<button id="city-input-btn"
					onclick="weatherFn($('#city-input').val())">
					Get Weather
			</button>
			<div id="weather-info"
				class="animate__animated animate__fadeIn">
				<h3 id="city-name"></h3>
				<p id="date"></p>
				<img id="weather-icon" src="" alt="Weather Icon">
				<p id="temperature"></p>
				<p id="description"></p>
				<p id="wind-speed"></p>
			</div>
		</div>
	</div>
	<script src=
"https://momentjs.com/downloads/moment.min.js">
	</script>
	<script src="script.js"></script>
</body>

</html>
style.css script.js

Step 5: Running the Application

  • Save all the files: Make sure the files index.html, styles.css, and script.js are saved properly.
  • Get Your API Key: Go to OpenWeatherMap, create an account, and get your free API key.
  • Open the app: Open index.html in your web browser. The app will initially show the weather for Pune.

Output:

Conclusion

You've built a functional Weather App using HTML, CSS, and JavaScript, which helps you practice working with APIs and DOM manipulation. You can enhance it further by adding features like:

  • Custom city input for weather searches.
  • A multi-day weather forecast.
  • Automatic weather detection based on the user's location.
  • Storing and displaying previous searches using local storage.

Next Article

Similar Reads