Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
48 lines (40 loc) · 1.62 KB
/
Copy pathapp.js
File metadata and controls
48 lines (40 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const apiKey = '9aeda0b53bd7959c3493bd0e657a1703'; // Replace with your OpenWeatherMap API key
const cityInput = document.getElementById('cityInput');
const searchBtn = document.getElementById('searchBtn');
const weatherResult = document.getElementById('weatherResult');
searchBtn.addEventListener('click', () => {
const city = cityInput.value.trim();
if (!city) {
alert('Please enter a city name.');
return;
}
weatherResult.innerHTML = '<p>Loading weather data...</p>';
weatherResult.classList.remove('hidden');
const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}&units=metric`;
console.log("Fetching weather for:", city);
console.log("API URL:", apiURL);
fetch(apiURL)
.then(response => {
console.log("Raw response:", response);
if (!response.ok) {
throw new Error('City not found. Try a different city.');
}
return response.json();
})
.then(data => {
console.log("Weather data:", data);
const iconCode = data.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;
weatherResult.innerHTML = `
<h2>${data.name}</h2>
<img src="${iconUrl}" alt="Weather icon">
<p><strong>Temperature:</strong> ${data.main.temp} °C</p>
<p><strong>Humidity:</strong> ${data.main.humidity}%</p>
<p><strong>Condition:</strong> ${data.weather[0].description}</p>
`;
})
.catch(error => {
console.error("Fetch error:", error.message);
weatherResult.innerHTML = `<p style="color: red;">${error.message}</p>`;
});
});