Why? Learn fetch()
API and working with JSON.
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
</head>
<body>
<h2>š¦ Weather App</h2>
<input type="text" id="city" placeholder="Enter city">
<button onclick="getWeather()">Search</button>
<p id="result"></p>
<script>
async function getWeather() {
let city = document.getElementById("city").value;
let apiKey = "your_api_key"; // get free key from openweathermap.org
let url = https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${apiKey}&amp;units=metric
;
let response = await fetch(url);
let data = await response.json();
if (data.cod === "404") {
document.getElementById("result").innerText = "City not found!";
} else {
document.getElementById("result").innerText =
`š ${data.name}, ${data.sys.country}
š” Temp: ${data.main.temp}°C
ā Weather: ${data.weather[0].description}`;
}
}
</script>
</body>
</html>
Explanation:
- User enters a city name.
fetch()
calls OpenWeatherMap API.- JSON data is parsed and displayed.
Leave a Reply