-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
141 lines (125 loc) · 5.73 KB
/
script.js
File metadata and controls
141 lines (125 loc) · 5.73 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
const OPENWEATHERMAP_API_KEY = "7691267e6e7246c1dafaf2a554521c70";
const API_URL = "https://api.openweathermap.org/data/2.5/weather";
const body = document.body;
const cityInput = document.getElementById('cityInput');
const searchButton = document.getElementById('searchButton');
const locationButton = document.getElementById('locationButton');
const weatherDetails = document.getElementById('weatherDetails');
const initialMessage = document.getElementById('initialMessage');
const welcomeText = document.getElementById('welcomeText');
const loadingSpinner = document.getElementById('loadingSpinner');
const errorMessage = document.getElementById('errorMessage');
const errorText = document.getElementById('errorText');
const cityName = document.getElementById('cityName');
const weatherDescription = document.getElementById('weatherDescription');
const temperature = document.getElementById('temperature');
const tempUnitSpan = document.getElementById('tempUnit');
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('windSpeed');
const weatherIcon = document.getElementById('weatherIcon');
function getBackgroundImageUrl(status) {
const overlay = 'linear-gradient(rgba(0,0,0,0.65), rgba(0,0,0,0.75))';
let img;
switch (status) {
case 'Clear':
img = 'https://cebudailynews.inquirer.net/files/2021/07/sunny.png';
break;
case 'Clouds':
img = 'https://www.shutterbug.com/images/styles/960-wide/public/photo_post/27425/Treasures%20are%20in%20the%20Sky.jpg';
break;
case 'Rain': case 'Drizzle':
img = 'https://img.freepik.com/premium-photo/immerse-yourself-harsh-reality-hailstorm-generative-ai_1198249-3793.jpg';
break;
case 'Thunderstorm':
img = 'https://img.freepik.com/premium-photo/cloudy-rainy-strom-black-clouds-cloud-cover-generate-ai_905417-2167.jpg';
break;
case 'Snow':
img = 'https://images.wallpapersden.com/image/download/winter-trees-snow-season_am5uaGeUmZqaraWkpJRqaWxnrWhrZWs.jpg';
break;
case 'Mist': case 'Haze': case 'Fog':
img = 'https://images7.alphacoders.com/660/thumb-1920-660728.jpg';
break;
default:
img = 'https://wallpaperaccess.com/full/535628.jpg';
}
return `${overlay}, url(${img})`;
}
function resetDisplay() {
weatherDetails.classList.add('hidden');
loadingSpinner.classList.add('hidden');
errorMessage.classList.add('hidden');
initialMessage.classList.add('hidden');
}
function displayError(msg, detail = '') {
resetDisplay();
errorMessage.classList.remove('hidden');
errorText.textContent = detail || msg;
searchButton.disabled = false;
locationButton.disabled = false;
console.error(msg, detail);
}
async function fetchWeather(query, isCoords = false) {
resetDisplay();
loadingSpinner.classList.remove('hidden');
searchButton.disabled = true;
locationButton.disabled = true;
let url = isCoords
? `${API_URL}?lat=${query.lat}&lon=${query.lon}&units=metric&appid=${OPENWEATHERMAP_API_KEY}`
: `${API_URL}?q=${encodeURIComponent(query)}&units=metric&appid=${OPENWEATHERMAP_API_KEY}`;
try {
const res = await fetch(url);
const data = await res.json();
if (data.cod !== 200) throw new Error(data.message || 'City not found');
displayWeather(data);
} catch (e) {
displayError("Failed to fetch weather", e.message);
} finally {
loadingSpinner.classList.add('hidden');
searchButton.disabled = false;
locationButton.disabled = false;
}
}
function displayWeather(data) {
resetDisplay();
weatherDetails.classList.remove('hidden');
const mainWeather = data.weather[0].main;
const backgroundImage = getBackgroundImageUrl(mainWeather);
body.style.backgroundImage = backgroundImage;
body.style.backgroundSize = 'cover';
body.style.backgroundPosition = 'center';
body.style.backgroundRepeat = 'no-repeat';
body.style.backgroundAttachment = 'fixed';
cityName.textContent = `${data.name}, ${data.sys.country}`;
weatherDescription.textContent = data.weather[0].description;
humidity.textContent = `${data.main.humidity}%`;
windSpeed.textContent = `${(data.wind.speed * 3.6).toFixed(1)} km/h`;
weatherIcon.src = `https://openweathermap.org/img/wn/${data.weather[0].icon}@4x.png`;
weatherIcon.alt = data.weather[0].description;
temperature.textContent = Math.round(data.main.temp);
tempUnitSpan.textContent = '°C';
}
function handleSearch() {
const city = cityInput.value.trim();
if(city) {
fetchWeather(city);
cityInput.value = '';
} else {
displayError("Please enter a city name.");
}
}
function fetchLocationWeather() {
if(!navigator.geolocation) return displayError("Geolocation not supported");
navigator.geolocation.getCurrentPosition(
pos => fetchWeather({ lat: pos.coords.latitude, lon: pos.coords.longitude }, true),
err => displayError("Location Error", err.message)
);
}
searchButton.addEventListener('click', handleSearch);
locationButton.addEventListener('click', fetchLocationWeather);
cityInput.addEventListener('keypress', e => { if(e.key==='Enter') handleSearch(); });
// Set initial background
body.style.backgroundImage = 'linear-gradient(rgba(0,0,0,0.65), rgba(0,0,0,0.75)), url(https://wallpaperaccess.com/full/535628.jpg)';
body.style.backgroundSize = 'cover';
body.style.backgroundPosition = 'center';
body.style.backgroundRepeat = 'no-repeat';
body.style.backgroundAttachment = 'fixed';