forked from deepspacerobots/code-test-zip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
56 lines (45 loc) · 1.74 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
54
55
56
let country = ''
let latitude = ''
let longitude = ''
let place = ''
let state = ''
let stateAbbrev = ''
const searchResults = document.getElementById('searchResults')
const errorMessage = document.getElementById('error')
document.getElementById('submit').addEventListener("click", fetchZIP)
function fetchZIP(e) {
e.preventDefault()
const zip = document.getElementById('zip').value
if (zip.length === 5) {
errorMessage.innerHTML = ""
searchResults.innerHTML = 'Searching...'
fetch(`http://api.zippopotam.us/us/${zip}`)
.then(response => response.json())
.then(data => {
country = data["country abbreviation"]
latitude = data.places[0].latitude
longitude = data.places[0].longitude
place = data.places[0]["place name"]
state = data.places[0].state
stateAbbrev = data.places[0]["state abbreviation"]
searchResults.classList.add('pre-animation')
setTimeout(function(){
searchResults.innerHTML = `
<div><p>${place}, ${state}, ${country}</p>
<p>Latitude: ${latitude}</p>
<p>Longitude: ${longitude}</p>
<p>Zip: ${zip}</p></div>
<img src='/states/${stateAbbrev}.svg'>
`
searchResults.classList.remove('pre-animation')
},1000)
document.getElementById('zip').value = ''
})
.catch(err => {
searchResults.innerHTML = "Oops. That zip code doesn't exist. Try another one."
document.getElementById('zip').value = ''
})
} else {
errorMessage.innerHTML = "Please enter a valid, 5-digit zip code."
}
}