-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
58 lines (46 loc) · 1.24 KB
/
main.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
const weatherDisplay = document.querySelector('.weather')
const weatherForm = document.querySelector('#weather-form')
const cityInput = document.querySelector('#city-input')
// Fetch weather data from API
const fetchWeather = async (city) => {
const url = `/api?q=${city}`
const res = await fetch(url)
const data = await res.json()
if (data.cod === '404') {
alert('City not found')
return
}
if (data.cod === 401) {
alert('Invalid API Key')
return
}
document.querySelector('.data').textContent = JSON.stringify(data);
const displayData = {
city: data.name,
temp: kelvinToFahrenheit(data.main.temp),
}
addWeatherToDOM(displayData)
}
// Add display data to DOM
const addWeatherToDOM = (data) => {
weatherDisplay.innerHTML = `
<h1>Weather in ${data.city}</h1>
<h2>${data.temp} °F</h2>
`
cityInput.value = ''
}
// Convert Kelvin to Fahrenheit
const kelvinToFahrenheit = (temp) => {
return Math.ceil(((temp - 273.15) * 9) / 5 + 32)
}
// Event listener for form submission
weatherForm.addEventListener('submit', (e) => {
e.preventDefault()
if (cityInput.value === '') {
alert('Please enter a city')
} else {
fetchWeather(cityInput.value)
}
})
// Initial fetch
fetchWeather('Miami')