🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Project Setup
Create a Project Directory: Name it weather-app. This will organize your project files.
File Structure:
- index.html: Contains the markup for the application.
- style.css: Styles the application.
- script.js: Contains the logic to fetch and display weather data.
Development Steps
1. HTML Markup (index.html)
- Start with a basic HTML structure. Link your CSS and JavaScript files.
- Create a form with an input field for the user to search by location (e.g., city name).
- Include a main element (<main>) where the weather data will be displayed.
Let's open the index.html file and add the following code to it:
<!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" />
<script src="script.js" defer></script>
</head>
<body>
<form id="form">
<input
type="text"
id="search"
placeholder="Search by location"
autocomplete="off"
/>
</form>
<main id="main"></main>
</body>
</html>
2. Styling (style.css)
- Apply global styles and import a font from Google Fonts for a clean look.
- Style the input field with rounded corners and a box shadow for depth.
- Design the weather display section to center content and enhance the visibility of weather information.
Let's open the style.css file and add the following CSS code to it:
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");
* {
box-sizing: border-box;
}
body {
background: linear-gradient(300deg, #ced1d6, #bfc0c0);
font-family: "Poppins", sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
min-height: 100vh;
}
input {
background-color: #fff;
border: none;
border-radius: 25px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
font-family: inherit;
font-size: 1rem;
padding: 1rem;
min-width: 300px;
}
input:focus {
outline: none;
}
.weather {
font-size: 2rem;
text-align: center;
}
.weather h2 {
display: flex;
align-items: center;
margin-bottom: 0;
}
3. JavaScript Logic (script.js)
Initialization:
- Define your API key from OpenWeatherMap.
- You’ll need to sign up for a free API key at OpenWeatherMap to use their service.
- Select the DOM elements you will interact with: the form, search input, and main content area.
Fetching Weather Data:
- Construct the API URL to fetch weather data for the user-specified location.
- Create an asynchronous function to fetch weather data using the Fetch API, then parse the response as JSON.
- Handle errors gracefully to alert the user if the data cannot be retrieved.
Displaying Weather Data:
- Convert the temperature from Kelvin to Celsius for readability.
- Create a function to update the DOM with the weather data, including the temperature, weather conditions, and an icon representing the weather.
- Clear the previous search results each time new data is fetched.
Event Handlers:
- Add an event listener to the form to prevent the default submit action and call the function to fetch and display weather data when a user searches for a location.
Let's open the script.js file and add the following JavaScript code to it:
const apikey = "3265874a2c77ae4a04bb96236a642d2f";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
const url = (city) =>
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`;
async function getWeatherByLocation(city) {
const resp = await fetch(url(city), { origin: "cors" });
const respData = await resp.json();
console.log(respData);
addWeatherToPage(respData);
}
function addWeatherToPage(data) {
const temp = KtoC(data.main.temp);
const weather = document.createElement("div");
weather.classList.add("weather");
weather.innerHTML = `
<h2><img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /></h2>
<small>${data.weather[0].main}</small>
`;
// cleanup
main.innerHTML = "";
main.appendChild(weather);
}
function KtoC(K) {
return Math.floor(K - 273.15);
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const city = search.value;
if (city) {
getWeatherByLocation(city);
}
});Open index.html in Browser
Let's open the index.html file in the browser, and you will be able to see the following screen:Conclusion
Following these steps, you've created a functional Weather App that can provide real-time weather updates for different locations. This project introduces you to working with APIs, asynchronous JavaScript, and dynamically updating the HTML with JavaScript.
Feel encouraged to expand on this project:
- Implement error handling for invalid location searches.
- Add more weather details like wind speed, humidity, and pressure.
- Explore adding a feature to switch between Celsius and Fahrenheit.
- Consider implementing a feature that uses the user's current location to fetch weather data automatically.
This Weather App project serves as a practical introduction to creating web applications with JavaScript. It showcases the power of APIs in integrating dynamic data into projects.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business

Comments
Post a Comment
Leave Comment