-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
197 lines (148 loc) · 5.83 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const form = document.getElementById('search-form')
const container = document.querySelector('.card-container')
const states = document.getElementById('states')
const card = document.querySelector('#card')
//EVENT LISTENERS
//Populate card container after DOM loads
document.addEventListener('DOMContentLoaded', preloadLocations)
form.addEventListener('submit', handleSubmit)
function handleSubmit(e){
e.preventDefault()
//create location object (posts to db.json) from search input
let newLocationObject = {
city: e.target.city.value,
st: e.target.states.value,
state: states.options[states.selectedIndex].text,
stateStr: `${e.target.city.value.replace(' ','-')}-${e.target.states.value}`.toLowerCase(),
}
//Rendering card to page
getData(newLocationObject, renderCard)
// //Resetting form
form.reset()
}
//RENDER NEW CARD
function renderCard(location, income, age, property, population){
//Create card that renders after form submission
const newCard = document.createElement('div')
newCard.id = 'card'
container.append(newCard)
//Create close button
const closeButton = document.createElement('div')
closeButton.className = 'close-btn'
newCard.append(closeButton)
const closeIcon = document.createElement('img')
closeIcon.className = 'icon'
closeIcon.src = "./media/xmark-solid.png"
closeButton.append(closeIcon)
//Delete entire card when close icon is clicked
closeButton.addEventListener('click', (e) => console.log(e.target.parentElement.parentElement.remove()))
//Create Card Header (location Info)
const cardHeader = document.createElement('div')
cardHeader.className = 'card-header'
const h3 = document.createElement('h3')
h3.textContent = location.city
h3.className = 'city'
cardHeader.append(h3)
const h4 = document.createElement('h4')
h4.textContent = `${location.state}, USA`
h4.className = 'state'
cardHeader.append(h4)
const stateFlag = document.createElement('img')
stateFlag.src = `https://www.states101.com/img/flags/svg/${location.state.toLowerCase().replace(' ','-')}.svg`
stateFlag.id = 'flag'
cardHeader.append(stateFlag)
newCard.append(cardHeader)
//Line of seperation
const hr = document.createElement('hr')
newCard.append(hr)
//Create data div that populates with fetched info from API
const dataDiv = document.createElement('div')
const incomeP = document.createElement('p')
const ageP = document.createElement('p')
const propertyP = document.createElement('p')
const populationP = document.createElement('p')
dataDiv.append(incomeP, ageP, propertyP, populationP)
dataDiv.className = 'data-div'
newCard.append(dataDiv)
incomeP.innerHTML = `
Median Income: <span class='data'>${income}</span>
`
ageP.innerHTML = `
Median Age: <span class='data'>${age} years</span>
`
propertyP.innerHTML = `
Median Property Value: <span class='data'>${property}</span>
`
populationP.innerHTML = `
MSA Population: <span class='data'>${population}</span>
`
}
//FETCH REQUESTS
//GET DATA USING ASYNC FUNCTIONS & AWAIT
async function getData(loc, callback){
const location = loc.stateStr;
let incomeData, ageData, propertyData, populationData;
try {
incomeData = await fetch(`https://datausa.io/api/data?measure=Household%20Income%20by%20Race,Household%20Income%20by%20Race%20Moe&Geography=${location}:similar&year=latest`)
.then(res => res.json())
.then(d => updateIncome(d))
ageData = await fetch(`https://datausa.io/api/data?measure=Median%20Age&Geography=${location}:parents&year=latest`)
.then(response => response.json())
.then(d => updateAge(d))
propertyData = await fetch(`https://datausa.io/api/data?measure=Property%20Value&Geography=${location}:parents&year=latest`)
.then(res => res.json())
.then(d => updateProperty(d))
populationData = await fetch(`https://datausa.io/api/data?measure=Population&Geography=${location}:parents&year=latest`)
.then(res => res.json())
.then(d => updatePopulation(d))
} catch(error){
console.log(error)
} finally{
callback(loc, incomeData, ageData, propertyData, populationData)
}
}
//RENDER UPDATES
function updateIncome(d){
const householdIncome = d.data.slice(-1)['0']['Household Income by Race'].toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
});
// console.log(householdIncome)
return householdIncome;
}
function updateAge(d){
const age = d.data.slice(-1)['0']['Median Age']
return age;
}
function updateProperty(d){
const propertyValue = d.data.slice(-1)['0']['Property Value'].toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
});
return propertyValue;
}
function updatePopulation(d){
const population = d.data.slice(-1)['0']['Population'].toLocaleString()
return population;
}
//PRE-LOADED LOCATIONS
const randomLocations = [
['Denver', 'CO', 'Colorado'],
['Cincinnati', 'OH', 'Ohio'],
['Boston', 'MA', 'Massachusetts'],
]
function preloadLocation(city, st, state){
let preloadedLocation = {
city: city.toString(),
st: st.toString(),
state: state.toString(),
stateStr: `${city.replace(' ','-').toLowerCase()}-${st.toLowerCase()}`,
}
//Rendering card to page
getData(preloadedLocation, renderCard)
}
function preloadLocations(){
randomLocations.forEach(location => preloadLocation(location[0], location[1], location[2]))
}