-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (53 loc) · 2.31 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
const api = {
key:"28fd15358cdecbc1a1dfef367e71acef",
base: "api.openweathermap.org/data/2.5/"
}
const search = document.querySelector(".search");
const btn = document.querySelector(".button-submit");
btn.addEventListener("click", getInput);
function getInput (event) {
event.preventDefault();
if (event.type == "click") {
getData(search.value);
//console.log(search.value);
//console.log(`${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`);
}
}
function getData () {
fetch(`https://${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`)
.then(response => {
return response.json();
}).then(displayData);
}
function displayData (response) {
console.log(response);
if (response.cod === "404") {
const error = document.querySelector(".error");
error.textContent = "Please enter a valid city";
search.value = "";
} else {
const error = document.querySelector(".error");
error.textContent = "";
const city = document.querySelector(".city");
city.innerText = `${response.name}, ${response.sys.country}`;
const today = new Date();
const date = document.querySelector(".date");
date.innerText = dateFunction(today);
const temp = document.querySelector(".temp");
temp.innerHTML = `Temp: ${Math.round(response.main.temp)} <span>°C</span>`;
const weather = document.querySelector(".weather");
weather.innerText = `Weather: ${response.weather[0].main}`;
const tempRange = document.querySelector(".temp-range");
tempRange.innerText = `Temp Range: ${Math.round(response.main.temp_min)}°C / ${Math.round(response.main.temp_max)}°C`;
search.value = "";
}
}
function dateFunction (d) {
let months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = d.getFullYear();
return `${day}, ${date} ${month} ${year}`;
}