|
| 1 | +const api = { |
| 2 | + key:"28fd15358cdecbc1a1dfef367e71acef", |
| 3 | + base: "api.openweathermap.org/data/2.5/" |
| 4 | +} |
| 5 | + |
| 6 | +const search = document.querySelector(".search"); |
| 7 | +const btn = document.querySelector(".button-submit"); |
| 8 | +btn.addEventListener("click", getInput); |
| 9 | + |
| 10 | +function getInput (event) { |
| 11 | + event.preventDefault(); |
| 12 | + if (event.type == "click") { |
| 13 | + getData(search.value); |
| 14 | + //console.log(search.value); |
| 15 | + //console.log(`${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +function getData () { |
| 20 | + fetch(`https://${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`) |
| 21 | + .then(response => { |
| 22 | + return response.json(); |
| 23 | + }).then(displayData); |
| 24 | + |
| 25 | +} |
| 26 | + |
| 27 | +function displayData (response) { |
| 28 | + console.log(response); |
| 29 | + if (response.cod === "404") { |
| 30 | + const error = document.querySelector(".error"); |
| 31 | + error.textContent = "Please enter a valid city"; |
| 32 | + search.value = ""; |
| 33 | + } else { |
| 34 | + const error = document.querySelector(".error"); |
| 35 | + error.textContent = ""; |
| 36 | + const city = document.querySelector(".city"); |
| 37 | + city.innerText = `${response.name}, ${response.sys.country}`; |
| 38 | + |
| 39 | + const today = new Date(); |
| 40 | + const date = document.querySelector(".date"); |
| 41 | + date.innerText = dateFunction(today); |
| 42 | + |
| 43 | + const temp = document.querySelector(".temp"); |
| 44 | + temp.innerHTML = `Temp: ${Math.round(response.main.temp)} <span>°C</span>`; |
| 45 | + |
| 46 | + const weather = document.querySelector(".weather"); |
| 47 | + weather.innerText = `Weather: ${response.weather[0].main}`; |
| 48 | + |
| 49 | + const tempRange = document.querySelector(".temp-range"); |
| 50 | + tempRange.innerText = `Temp Range: ${Math.round(response.main.temp_min)}°C / ${Math.round(response.main.temp_max)}°C`; |
| 51 | + |
| 52 | + search.value = ""; |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +function dateFunction (d) { |
| 57 | + let months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"]; |
| 58 | + let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; |
| 59 | + |
| 60 | + let day = days[d.getDay()]; |
| 61 | + let date = d.getDate(); |
| 62 | + let month = months[d.getMonth()]; |
| 63 | + let year = d.getFullYear(); |
| 64 | + |
| 65 | + return `${day}, ${date} ${month} ${year}`; |
| 66 | +} |
0 commit comments