forked from ejhessing/dom-events-and-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
83 lines (70 loc) · 2.21 KB
/
game.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
// Don't change or delete this line! It waits until the DOM has loaded, then calls
// the start function. More info:
// https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
document.addEventListener('DOMContentLoaded', start)
function start () {
bindEventListeners(document.getElementsByClassName('board')[0].children)
}
function bindEventListeners (dots) {
for (var i = 0; i < dots.length; i++) {
// BIND YOUR EVENT LISTENERS HERE
// The first one is provided for you
dots[i].addEventListener('contextmenu', makeGreen)
dots[i].addEventListener('click', makeBlue)
dots[i].addEventListener('dblclick', hide, function (evt) {
evt.bindEventListeners(hide)
});
}
}
function makeGreen (evt) {
evt.preventDefault();
resetClass (evt);
evt.target.classList.toggle('green');
updateCounts();
}
function makeBlue(evt) {
resetClass (evt);
evt.target.classList.toggle('blue');
updateCounts();
}
function hide (evt) {
resetClass (evt);
evt.target.classList.toggle('invisible');
updateCounts();
}
// function to reset count, as explained by the brilliant Sherly //
function resetClass (evt){
if (evt.target.classList.contains('green')) {
evt.target.classList.remove('green');
} else if (evt.target.classList.contains('blue')){
evt.target.classList.remove('blue');
} else if (evt.target.classList.contains('invisible')){
evt.target.classList.remove('invisible');
}
}
function updateCounts () {
var totals = {
blue: 0,
green: 0,
invisible: 0
}
// WRITE CODE HERE TO COUNT BLUE, GREEN, AND INVISIBLE DOTS
var addTotals =
document.getElementsByClassName('board')[0].children;
for (i=0; i<addTotals.length; i++) {
if (addTotals[i].classList.contains('blue')) {
totals.blue +=1
} else if (addTotals[i].classList.contains('green')) {
totals.green += 1
} else if (addTotals[i].classList.contains('invisible')) {
totals.invisible += 1
}
}
// Once you've done the counting, this function will update the display
displayTotals(totals)
}
function displayTotals (totals) {
for (var key in totals) {
document.getElementById(key + '-total').innerHTML = totals[key]
}
}