-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
49 lines (45 loc) · 1.99 KB
/
script.js
File metadata and controls
49 lines (45 loc) · 1.99 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
document.getElementById("getWeather").addEventListener("click", function () {
const city = document.getElementById("city").value;
const apiKey = "";
const url = `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${city}&aqi=yes`;
fetch(url)
.then((response) => response.json())
.then((data) => {
// Get the Responses
const temp = data.current.temp_c;
const humidity = data.current.humidity;
const windSpeed = data.current.wind_kph;
const condition = data.current.condition.text;
const location = `${data.location.name}, ${data.location.country}`;
const latest = data.current.last_updated;
//Format
const date = new Date(latest);
const options = { month: "short", day: "numeric", year: "numeric" };
const formattedDate = new Intl.DateTimeFormat("en-US", options).format(
date
);
// Extract Time
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const formattedTime = `${hours}:${minutes}`;
// Combine
const formattedDateTime = `${formattedDate}, ${formattedTime}`;
// Display Results
document.getElementById("location").textContent = location;
document.getElementById(
"latest"
).textContent = `${formattedDateTime}`;
document.getElementById("temperature").textContent = `${temp}°C`;
document.getElementById("humidity").textContent = `${humidity}%`;
document.getElementById("windspeed").textContent = `${windSpeed} km/h`;
document.getElementById("condition").textContent = `${condition}`;
})
.catch((error) => {
document.getElementById("temperature").textContent = "?";
document.getElementById("humidity").textContent = "?";
document.getElementById("windspeed").textContent = "?";
document.getElementById("condition").textContent = "?";
console.error("Error:", error);
alert("City Not Found, Try Again!");
});
});