-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (39 loc) · 1.97 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
const apiKey ="1e402c19e3ff3cc8ff5d926d3b5bd78e"
const weatherDataEle = document.querySelector(".weather-data")
const cityNameEle = document.querySelector("#city-name")
const formEle = document.querySelector("form")
const imgIcon = document.querySelector(".icon")
formEle.addEventListener("submit", (e)=>{
e.preventDefault()
// console.log(cityNameEle.value);
const cityValue = cityNameEle.value
getWeatherData(cityValue)
})
async function getWeatherData(cityValue){
try{
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityValue}&appid=${apiKey}&units=metric`)
if(!response.ok){
throw new Error("Network response is not ok!")
}
const data = await response.json()
// console.log(data);
const temprature = Math.floor(data.main.temp)
const description = data.weather[0].description
const icon = data.weather[0].icon
const details = [
`Feels Like: ${Math.floor(data.main.feels_like)}°C`,
`Humidity: ${data.main.humidity}%`,
`Wind Speed: ${data.wind.speed} m/s`
]
weatherDataEle.querySelector(".temp").textContent = `${temprature}°C`
weatherDataEle.querySelector(".desc").textContent = `${description}`
imgIcon.innerHTML = `<img src="https://openweathermap.org/img/wn/${icon}.png" alt="">`
weatherDataEle.querySelector(".details").innerHTML = details.map((detail)=>{
return `<div>${detail}</div>`
}).join("")
}catch(err){
weatherDataEle.querySelector(".temp").textContent = ""
imgIcon.innerHTML = ""
weatherDataEle.querySelector(".desc").textContent = "An Error Occurred!"
}
}