-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (41 loc) · 1.79 KB
/
Copy pathindex.js
File metadata and controls
62 lines (41 loc) · 1.79 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
// Initializing all elements constants
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");
let target = 'Canada'; // by default
const fetchData = async(target) => {
try { // if input is valid
const url = `https://api.weatherapi.com/v1/current.json?key=a384be39d4424a80b74131447232601&q=${target}`;
const response = await fetch(url); // fetches data from apui
const data = await response.json(); // json to data form
const fTemp = data.current.temp_c;
const fcity = data.location.name ;
const fWeather = data.current.condition.text ;
const fDate = data.location.localtime;
const fEmoji = data.current.condition.icon
updateDom(fTemp,fcity,fWeather,fDate,fEmoji);
} catch {
// if input is not valid
alert('Location not found ');
}
};
fetchData(target); // function call
// function for manupilating DOM Elements
function updateDom (temp,city,weather,date,emoji) {
temperateField.innerText = temp;
cityField.innerText = city ;
emojiField.src = emoji ;
weatherField.innerText = weather;
dateField.innerText = date;
};
// adding eventListener to the Form
form.addEventListener("submit",(e)=>{
e.preventDefault(); // to avoid reload on submit action
target = searchField.value;
// console.log(target); test
fetchData(target);
})