This tutorial will guide you through the process of creating a simple weather app. We will use HTML, CSS, and JavaScript to build a user-friendly interface that fetches weather data from an API and displays it to the user.
Prerequisites
Before you start, make sure you have the following:
- Basic knowledge of HTML, CSS, and JavaScript
- A text editor (e.g., Visual Studio Code, Sublime Text)
- A web browser
Step 1: Set up the Project
- Create a new folder on your computer and name it "weather-app".
- Open the folder in your text editor.
- Create a new HTML file named "index.html" and add the following code:
<!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="styles.css">
</head>
<body>
<div class="container">
<h1>Weather App</h1>
<input type="text" id="cityInput" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div id="weatherDisplay"></div>
</div>
<script src="script.js"></script>
</body>
</html>
- Create a new CSS file named "styles.css" and add the following code:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 5px;
}
button {
width: 100%;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #5cb85c;
color: white;
cursor: pointer;
}
button:hover {
background-color: #4cae4c;
}
#weatherDisplay {
margin-top: 20px;
padding: 20px;
background-color: #e9ecef;
border-radius: 5px;
}
- Create a new JavaScript file named "script.js" and add the following code:
function getWeather() {
const cityInput = document.getElementById("cityInput").value;
const weatherDisplay = document.getElementById("weatherDisplay");
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityInput}&appid=YOUR_API_KEY&units=metric`)
.then(response => response.json())
.then(data => {
weatherDisplay.innerHTML = `
<h2>${data.name}</h2>
<p>Temperature: ${data.main.temp}°C</p>
<p>Weather: ${data.weather[0].description}</p>
`;
})
.catch(error => {
weatherDisplay.innerHTML = "Error: " + error.message;
});
}
Replace YOUR_API_KEY
with your OpenWeatherMap API key.
Step 2: Run the App
- Open the "index.html" file in your web browser.
- Enter a city name in the input field and click the "Get Weather" button.
- The weather information for the specified city will be displayed on the page.
For more information on how to create a weather app, check out our Weather App Advanced Tutorial.