-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
101 lines (89 loc) · 2.44 KB
/
app.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
;(function() {
'use strict'
/**
* Element.closest() polyfill
* https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
*/
if (!Element.prototype.closest) {
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector
}
Element.prototype.closest = function(s) {
var el = this
var ancestor = this
if (!document.documentElement.contains(el)) return null
do {
if (ancestor.matches(s)) return ancestor
ancestor = ancestor.parentElement
} while (ancestor !== null)
return null
}
}
/**
* Randomly shuffle an array
* https://stackoverflow.com/a/2450976/1293256
* @param {Array} array The array to shuffle
* @return {String} The first item in the shuffled array
*/
const shuffle = function(array) {
let currentIndex = array.length
let temporaryValue, randomIndex
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// And swap it with the current element.
temporaryValue = array[currentIndex]
array[currentIndex] = array[randomIndex]
array[randomIndex] = temporaryValue
}
return array
}
// The monsters and socks
const monsters = [
'monster1',
'monster2',
'monster3',
'monster4',
'monster5',
'monster6',
'monster7',
'monster8',
'monster9',
'monster10',
'monster11',
'sock'
]
const app = document.querySelector('#app')
function handleClick(e) {
const button = e.target.closest('data-monster-id')
if (!button) return
const index = button.getAttribute('data-monster-id')
button.parentNode.innerHTML = `<img src="assets/svg/${monsters[index]}.svg" alt="${monsters[index]}">`
}
function createCells(monsters) {
return monsters.map(
(_, index) =>
`<button type="button" data-monster-id="${index}"><img src="assets/svg/door.svg" alt="Click the door to see what\'s behind it"></button>`
)
}
function buildGrid() {
const cells = createCells(monsters)
return (
'<p>Click a door to reveal a monster. Try not to find the sock.</p>' +
'<div class="row">' +
shuffle(cells)
.map(item => `<div class="grid" aria-live="polite">${item}</div>`)
.join('') +
'</div>'
)
}
function renderGrid() {
app.innerHTML = buildGrid()
}
renderGrid()
document.addEventListener('click', handleClick, false)
})()