-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (70 loc) · 2.17 KB
/
index.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
82
83
84
85
86
87
88
89
90
91
92
93
94
const temperateField = document.querySelector(".weather1");
const cityField = document.querySelector(".weather2 p");
const dateField = document.querySelector(".weather2 span");
const emojiField = document.querySelector(".weather3 img");
const weatherField = document.querySelector(".weather3 span");
const searchField = document.querySelector(".searchField");
const form = document.querySelector("form");
// Adding event listen to the form
form.addEventListener("submit", search);
// Default Location
let target = "delhi";
// Function to fetch Data from Weather API
const fetchData = async (target) => {
try {
const url = `https://api.weatherapi.com/v1/current.json?key=3fe0edc1dcaf47c2b2e120858231406&q=${target}`;
const response = await fetch(url);
const data = await response.json();
// Destructuring
const {
current: {
temp_c,
condition: { text, icon },
},
location: { name, localtime },
} = data;
// Calling update Dom Function
updateDom(temp_c, name, localtime, icon, text);
} catch (error) {
alert("Location not found");
}
};
// Function to update Dom
function updateDom(temperate, city, time, emoji, text) {
const exactTime = time.split(" ")[1];
const exactDate = time.split(" ")[0];
const exactDay = getDayFullName(new Date(exactDate).getDay());
temperateField.innerText = temperate;
cityField.innerText = city;
dateField.innerText = `${exactTime} - ${exactDay} ${exactDate}`;
emojiField.src = emoji;
weatherField.innerText = text;
}
fetchData(target);
// Function to search the location
function search(e) {
e.preventDefault();
target = searchField.value;
fetchData(target);
}
// Function to get the name of day
function getDayFullName(num) {
switch (num) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturdat";
default:
return "Don't Know";
}
}