-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
76 lines (64 loc) · 2.48 KB
/
Copy pathscript.js
File metadata and controls
76 lines (64 loc) · 2.48 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
75
76
const apiKey = "f82b7cf775bc52a65102d85845062e3f";
async function getWeather() {
const city = document.getElementById("cityInput").value.trim();
if (!city) {
alert("Please enter a city name.");
return;
}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error("City not found");
const data = await response.json();
showWeather(data);
} catch (error) {
document.getElementById("weatherResult").innerHTML = `<p>${error.message}</p>`;
}
}
function showWeather(data) {
const { name, main, weather, wind } = data;
document.getElementById("weatherResult").innerHTML = `
<h2>${name}</h2>
<p><strong>🌡 Temp:</strong> ${main.temp}°C</p>
<p><strong>☁ Condition:</strong> ${weather[0].main} (${weather[0].description})</p>
<p><strong>💧 Humidity:</strong> ${main.humidity}%</p>
<p><strong>🌬 Wind:</strong> ${wind.speed} m/s</p>
`;
updateBackground(weather[0].main.toLowerCase());
}
function updateBackground(condition) {
const body = document.body;
body.className = ""; // Remove previous class
if (condition.includes("clear")) {
body.classList.add("sunny");
} else if (condition.includes("cloud")) {
body.classList.add("cloudy");
} else if (condition.includes("rain") || condition.includes("drizzle")) {
body.classList.add("rainy");
} else if (condition.includes("thunderstorm")) {
body.classList.add("thunder");
} else if (condition.includes("snow")) {
body.classList.add("snowy");
} else if (condition.includes("mist") || condition.includes("fog") || condition.includes("haze")) {
body.classList.add("misty");
} else {
body.classList.add("default");
}
}
// Auto detect user's location
window.onload = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(async (position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
const data = await response.json();
showWeather(data);
} catch (error) {
document.getElementById("weatherResult").innerHTML = `<p>Unable to fetch location-based weather data.</p>`;
}
});
}
};