-
Notifications
You must be signed in to change notification settings - Fork 5
/
ajaxAhead.jade
66 lines (51 loc) · 1.94 KB
/
ajaxAhead.jade
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
extends base
block vars
- var title = 'Ajax Type Ahead'
block styles
link(rel="stylesheet" type="text/css" href="styles/ajaxAhead.css")
block body
form
input.search(type="text" placeholder="City or State")
ul.suggestions
li Filter for a city
li or a state
script(type="text/javascript").
const endpoint = "https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json"
const cities = []
const $search = document.querySelector('.search')
const $suggestions = document.querySelector('.suggestions')
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data))
function match(word, cities) {
return cities.filter(place => {
const regex = new RegExp(word, 'gi')
return place.city.match(regex) || place.state.match(regex)
})
}
function commas(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function matches() {
const result = match(this.value, cities)
const bindHTML = result.map(place => {
const regex = new RegExp(this.value, 'gi')
const highlight = `<span class="hl">${this.value}</span>`
const cityName = place.city.replace(regex, highlight)
const stateName = place.state.replace(regex, highlight)
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${commas(place.population)}</span>
</li>
`
}).join('')
$suggestions.innerHTML = bindHTML
}
function addMultipleListeners(elem, e, handler) {
if (!(e instanceof Array))
throw 'addMultipleListeners: please supply an array of eventstrings (like ["click","mouseover"])'
for (let i = 0; i < e.length; i++)
elem.addEventListener(e[i], handler)
}
addMultipleListeners($search, ['change', 'keyup'], matches)