Code Below:
<!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>
<style>
body {
font-family: Arial, sans-serif;
background: #ccc;
text-align: center
}
.container {
max-width: 400px;
margin: 50px auto;
padding: 20px;
border-radius: 10px;
background-color: rgba(255, 255, 255, 0.8)
}
.weather-thumbnail {
width: 50px;
height: 50px;
margin: 10px
}
</style>
</head>
<body>
<div class="container">
<h2>Weather App</h2>
<input id="cityInput" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div id="weatherData"></div>
</div>
<script>
function getWeather() {
const c = document.getElementById('cityInput').value;
const k = 'd9680370698e25d5baff0233989f8bbc';
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${c}&appid=${k}&units=imperial`).then(r => r.json()).then(d => {
const w = document.getElementById('weatherData');
if (d.cod === 200) {
const i = `
<h3>${d.name}, ${d.sys.country}</h3>
<p>Temperature: ${d.main.temp} °F</p>
<p>Description: ${d.weather[0].description}</p>
<p>Humidity: ${d.main.humidity}%</p>
<img src="https://openweathermap.org/img/wn/${d.weather[0].icon}.png" alt="Weather Thumbnail" class="weather-thumbnail">`;
w.innerHTML = i;
document.body.style.backgroundImage = `url('${g(d.weather[0].main)}')`
} else {
w.innerHTML = `
<p>${d.message}</p>`
}
}).catch(e => {
console.error('Error fetching weather data:', e)
})
}
function g(w) {
switch (w.toLowerCase()) {
case 'clear':
return 'https://source.unsplash.com/featured/?sky';
case 'clouds':
return 'https://source.unsplash.com/featured/?clouds';
case 'rain':
return 'https://source.unsplash.com/featured/?rain';
case 'snow':
return 'https://source.unsplash.com/featured/?snow';
case 'thunderstorm':
return 'https://source.unsplash.com/featured/?thunderstorm';
case 'drizzle':
return 'https://source.unsplash.com/featured/?drizzle';
default:
return 'https://source.unsplash.com/featured/?weather'
}
}
</script>
</body>
</html>