Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Build A Weather App in HTML CSS & JavaScript
Next article icon

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.

HTML
<!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:

CSS
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.

JavaScript
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
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); } 
script.js
const url = 	'https://api.openweathermap.org/data/2.5/weather'; const apiKey = 	'f00c38e0279b7bc85480c3fe775d518c';  $(document).ready(function () { 	weatherFn('Noida'); // Set Noida as the initial city });  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')); // Corrected date format to include year 	$('#temperature'). 		html(`${Math.round(data.main.temp)}°C`); // Rounded temperature 	$('#description'). 		text(data.weather[0].description); 	$('#wind-speed'). 		html(`Wind Speed: ${data.wind.speed} m/s`); 	$('#weather-icon'). 		attr('src', 			`http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`); // Corrected icon URL 	$('#weather-info').fadeIn(); } 

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
Build A Weather App in HTML CSS & JavaScript

G

gpancomputer
Improve
Article Tags :
  • Project
  • JavaScript
  • Web Technologies
  • Dev Scripter
  • JavaScript-Projects
  • Dev Scripter 2024

Similar Reads

    Create a Weather App in HTML Bootstrap & JavaScript
    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 s
    3 min read
    Build an AI Image Generator Website in HTML CSS and JavaScript
    Create an AI image generator website using HTML, CSS, and JavaScript by developing a user interface that lets users input text prompts and generate images by AI.We incorporated API integration to fetch data, providing users with an effortless and dynamic experience in generating AI-driven images. An
    4 min read
    Building A Weather App Using VueJS
    We will explore how to create a weather application using Vue.js. We'll cover an approach to fetching weather data, displaying current weather conditions, and forecasting. By the end of this guide, you'll have a fully functional weather application that displays current weather information and forec
    6 min read
    Create a Build A Simple Alarm Clock in HTML CSS & JavaScript
    In this article, we will develop an interactive simple Alarm Clock application using HTML, CSS, and JavaScript languages.Develop an alarm application featuring date and time input fields for setting alarms. Implement comprehensive validation to prevent duplicate alarms and enforce a maximum limit of
    5 min read
    Design a Student Attendance Portal in HTML CSS & JavaScript
    The Student Attendance Portal is a web application that allows users to mark attendance for students in different classes, add class and students according to requirements, providing a user-friendly interface to update and visualize attendance records. Final Output PreviewApproach:In the first step,
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences