-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathscript.js
81 lines (76 loc) · 2.71 KB
/
script.js
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
const input = document.getElementById("input");
const btn = document.getElementById("btn");
const apiKey = "e3a46268fdc2475cb63214712240202";
const cityName = document.getElementById("city-name");
const dateTime = document.getElementById("date-time");
const condition = document.getElementById("condition");
const condition2 = document.getElementById("condition2");
const temp = document.getElementById("temp");
const humidity = document.getElementById("humidity");
const country = document.getElementById("country");
const locat = document.getElementById("getlocation");
const cities = document.getElementsByClassName("city");
const icon = document.getElementById("icon");
const fetchData = async (url) => {
try {
const data = await fetch(url);
if (!data.ok) {
throw new Error(data.statusText);
}
return data.json();
} catch (error) {
console.log(error);
throw error;
}
};
const updateWeatherInfo = (result) => {
cityName.innerText = `${result.location.name}`;
country.innerText = `${result.location.country}`;
dateTime.innerText = `${result.location.localtime}`;
temp.innerText = `${result.current.temp_c} °C`;
humidity.innerText = `${result.current.humidity} %`;
condition.innerText = `${result.current.condition.text}`;
condition2.innerText = `${result.current.condition.text}`;
icon.src = `${result.current.condition.icon}`; // Set the src attribute of the img tag with id "icon"
};
const getData = async (cityName) =>
fetchData(
`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${cityName}&aqi=no`
);
const getlocation = async (lat, long) =>
fetchData(
`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${lat},${long}&aqi=no`
);
const gotlocation = async (position) => {
try {
const result = await getlocation(
position.coords.latitude,
position.coords.longitude
);
updateWeatherInfo(result);
} catch (error) {
cityName.innerText = "Error fetching weather based on location";
}
};
const failedlocation = () => console.log("failed to locate location");
btn.addEventListener("click", async () => {
try {
const { value } = input;
const result = await getData(value);
updateWeatherInfo(result);
console.log(result);
} catch (error) {
cityName.innerText = "Error to fetch weather";
}
});
locat.addEventListener("click", () =>
navigator.geolocation.getCurrentPosition(gotlocation, failedlocation)
);
const citiesArray = [...cities];
citiesArray.forEach((element) => {
element.addEventListener("click", async () => {
const cityName = element.innerText; // Extract city name from the clicked element
const result = await getData(cityName); // Pass the city name to getData
updateWeatherInfo(result);
});
});