Weather Forecast Widget
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
padding: 0;
}
.container {
text-align: center;
}
h1 {
color: #333;
}
#weather-widget {
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#location {
margin-bottom: 20px;
}
input[type="text"] {
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
}
button {
background-color: #3498db;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
margin-left: 10px;
}
#weather-info p {
font-size: 18px;
margin: 5px 0;
}
// scripts.js
async function getWeather() {
const cityInput = document.getElementById('city-input').value.trim();
if (cityInput === '') {
alert('Please enter a city.');
return;
}
const API_KEY = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityInput}&appid=${API_KEY}&units=metric`;
try {
const response = await fetch(API_URL);
const data = await response.json();
if (data.cod === '404') {
alert('City not found. Please enter a valid city.');
return;
}
displayWeather(data);
} catch (error) {
console.error('Error fetching weather data:', error);
alert('An error occurred while fetching weather data. Please try again later.');
}
}
function displayWeather(data) {
const description = data.weather[0].description;
const temperature = `${data.main.temp}°C`;
const humidity = `Humidity: ${data.main.humidity}%`;
const windSpeed = `Wind Speed: ${data.wind.speed} m/s`;
document.getElementById('weather-description').textContent = `Weather: ${description}`;
document.getElementById('temperature').textContent = `Temperature: ${temperature}`;
document.getElementById('humidity').textContent = humidity;
document.getElementById('wind-speed').textContent = windSpeed;
}
No comments:
Post a Comment