-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
196 lines (164 loc) · 5.51 KB
/
script.js
File metadata and controls
196 lines (164 loc) · 5.51 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
document.addEventListener("DOMContentLoaded", () => {
const cityName = document.querySelector(".weather_city");
const searchCity = document.querySelector(".city_name");
const dateTime = document.querySelector(".weather_date_time");
const liveTime = document.querySelector(".live_date_time");
const container = document.querySelector(".container");
const w_forecast = document.querySelector(".weather_forecast");
const w_icon = document.querySelector(".weather_icon");
const w_temperature = document.querySelector(".weather_temperature");
const w_min = document.querySelector(".weather_min");
const w_max = document.querySelector(".weather_max");
const w_feelsLike = document.querySelector(".weather_feelsLike");
const w_humidity = document.querySelector(".weather_humidity");
const w_wind = document.querySelector(".weather_wind");
const w_pressure = document.querySelector(".weather_pressure");
let getCityName;
const loader = document.getElementById("loader");
// show loader
const showLoader = () => {
loader.style.display = "flex";
};
// hide loader
const hideLoader = () => {
loader.style.display = "none";
};
//* ✅ ONE TIME FORMAT (API + LIVE BOTH)
const formatTime = (date) => {
return new Intl.DateTimeFormat("en-US", {
weekday: "short",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: true,
}).format(date);
};
//* ✅ LIVE CLOCK +
setInterval(() => {
const now = new Date();
liveTime.innerHTML = `⏱ Now: ${formatTime(now)}`;
}, 1000);
//* UPDATED TIME SAME PLACE
const startClock = (dt) => {
const updated = new Date(dt * 1000);
dateTime.innerHTML = `⏳ Updated: ${formatTime(updated)} <br>`;
};
//* Country
const getCountryName = (code) =>
new Intl.DisplayNames(["en"], { type: "region" }).of(code);
//* API KEY
const api = "d7ec3135" + "875b5deb" + "e3d2628a" + "90742f65";
//* LocalStorage
const getCity = () => {
getCityName = JSON.parse(localStorage.getItem("City")) || ["Mumbai"];
return getCityName[0];
};
//* UI Update
const updateUI = (data) => {
const { main, name, weather, wind, sys, dt } = data;
cityName.innerHTML = `📍 ${name}, ${getCountryName(sys.country)}`;
//* 🔥 ONE CLOCK CALL
startClock(dt);
//* ✅ LIVE CLOCK +
const now = new Date();
liveTime.innerHTML = `⏱ Now: ${formatTime(now)}`;
setWeatherAnimation(weather[0].main);
w_forecast.innerHTML = weather[0].main;
w_icon.innerHTML = `<img src="https://openweathermap.org/img/wn/${weather[0].icon}@2x.png">`;
w_temperature.innerHTML = `${main.temp.toFixed()}°C`;
w_min.innerHTML = `Min: ${main.temp_min.toFixed()}°C`;
w_max.innerHTML = `Max: ${main.temp_max.toFixed()}°C`;
w_feelsLike.innerHTML = `${main.feels_like.toFixed()}°C`;
w_humidity.innerHTML = `${main.humidity}%`;
w_wind.innerHTML = `${wind.speed} m/s`;
w_pressure.innerHTML = `${main.pressure} hPa`;
};
//* Fetch
const fetchWeather = async (url) => {
const res = await fetch(url);
const data = await res.json();
if (data.cod !== 200) throw new Error("City not found");
return data;
};
//* Load Weather
const loadWeather = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(async (pos) => {
try {
const { latitude, longitude } = pos.coords;
showLoader();
const data = await fetchWeather(
`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${api}&units=metric`
);
updateUI(data);
hideLoader();
} catch {
fetchDefault();
hideLoader();
}
}, fetchDefault);
} else {
fetchDefault();
}
};
// 🌈 Weather Animation Control
const setWeatherAnimation = (type) => {
container.classList.remove("rain", "cloud", "sun", "night");
if (type.includes("Rain")) container.classList.add("rain");
else if (type.includes("Cloud")) container.classList.add("cloud");
else if (type.includes("Clear")) container.classList.add("sun");
else container.classList.add("night");
};
//* Default
const fetchDefault = async () => {
try {
showLoader();
const data = await fetchWeather(
`https://api.openweathermap.org/data/2.5/weather?q=${getCity()}&appid=${api}&units=metric`
);
updateUI(data);
hideLoader();
} catch {
toast("City not found 😬");
hideLoader();
}
hideLoader();
};
//* Search
const addCityName = async (e) => {
e.preventDefault();
const value = searchCity.value.trim();
if (!value) return;
try {
showLoader();
const data = await fetchWeather(
`https://api.openweathermap.org/data/2.5/weather?q=${value}&appid=${api}&units=metric`
);
getCityName = [value];
localStorage.setItem("City", JSON.stringify(getCityName));
searchCity.value = "";
updateUI(data);
hideLoader();
} catch {
console.log(searchCity.value);
toast(`${searchCity.value}\n❌ City not found`);
searchCity.value = "";
hideLoader();
}
};
//* Toast
const toast = (msg) => {
const t = document.createElement("div");
t.innerText = msg;
t.className = "toastMsg";
document.body.appendChild(t);
setTimeout(() => t.remove(), 1500);
};
//* Enter key
searchCity.addEventListener("keydown", (e) => {
if (e.key === "Enter") addCityName(e);
});
//* INIT
loadWeather();
});