Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
74 lines (62 loc) · 2.76 KB
/
Copy pathapp.js
File metadata and controls
74 lines (62 loc) · 2.76 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
document.addEventListener("DOMContentLoaded", () => {
const searchBtn = document.getElementById("searchBtn");
const cityInput = document.getElementById("cityInput");
const darkModeToggle = document.getElementById("darkModeToggle");
searchBtn.addEventListener("click", searchWeather);
cityInput.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
searchWeather();
}
});
darkModeToggle.addEventListener("change", toggleDarkMode);
// Load initial weather data
getWeather();
});
function searchWeather() {
const cityInput = document.getElementById("cityInput");
const cityName = cityInput.value.trim();
if (cityName !== "") {
getWeather(cityName);
} else {
alert("Please enter a city name.");
}
}
function getWeather(city) {
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=98740f4ebc0d63bc0f8ba70090e5a091`;
fetch(apiUrl)
.then((response) => response.json())
.then((data) => displayWeather(data, city))
.catch((error) => console.error("Error fetching weather data:", error));
}
function displayWeather(data, city) {
const cityElement = document.getElementById('city');
const temperatureElement = document.getElementById('temperature');
const descriptionElement = document.getElementById('description');
const windElement = document.getElementById('wind');
const cloudsElement = document.getElementById('clouds');
const iconElement = document.getElementById('icon');
if (data.cod === '404') {
// City not found
cityElement.textContent = `City not found: ${city}`;
temperatureElement.textContent = '';
descriptionElement.textContent = '';
windElement.textContent = '';
cloudsElement.textContent = '';
iconElement.innerHTML = `<img src="https://static-00.iconduck.com/assets.00/404-page-not-found-illustration-2048x998-yjzeuy4v.png" alt="Not Found Icon">`;
} else {
// City found, display weather information
cityElement.textContent = `Weather in ${city}`;
temperatureElement.textContent = `${data.main.temp}°C`;
descriptionElement.textContent = data.weather[0].description;
windElement.textContent = `Wind: ${data.wind.speed} m/s`;
cloudsElement.textContent = `Clouds: ${data.clouds.all}%`;
const iconUrl = data.weather[0].icon
? `http://openweathermap.org/img/w/${data.weather[0].icon}.png`
: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTruIUuHqZP9pIkCgeQSz0yCakJkqkS5V_8NnGJni4DBhskQNWa-Ur2hb6Lab4CWrVHlJM&usqp=CAU";
iconElement.innerHTML = `<img src="${iconUrl}" alt="Weather Icon">`;
}
}
function toggleDarkMode() {
const body = document.body;
body.classList.toggle("dark-mode");
}