-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
99 lines (93 loc) · 2.17 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
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
imgArray = [
{
name:"shelf",
img: './assets/1.jpg'
},
{
name:"building",
img: './assets/2.jpg'
},
{
name:"wall",
img: './assets/3.jpg'
},
{
name:"orange",
img: './assets/4.jpg'
},
{
name:"nature",
img: './assets/5.jpg'
},
{
name:"shelf",
img: './assets/6.jpg'
},
{
name:"drink",
img: './assets/7.jpg'
},
{
name:"orange",
img: './assets/8.jpg'
},
{
name:"nature",
img: './assets/9.jpg'
},
{
name:"building",
img: './assets/10.jpg'
},
{
name:"wall",
img: './assets/11.jpg'
},{
name:"drink",
img: './assets/12.jpg'
}
];
imgArray.sort(() => 0.5 - Math.random());
const gridElement = document.querySelector('.grid');
let chosenCards = [];
let chosenIds = [];
function fillGrid() {
imgArray.forEach((element,index) => {
const card = document.createElement('img');
card.setAttribute('src','./assets/blank.jpg');
card.setAttribute('alt','blank');
card.setAttribute('data-id',index);
card.addEventListener('click',flipCard);
gridElement.appendChild(card);
});
}
fillGrid();
function checkMatch() {
const cards = document.querySelectorAll('img');
setTimeout(()=> {
if(chosenCards[0] == chosenCards[1]) {
alert('right');
chosenIds.forEach((element)=> {
cards[element].setAttribute('src','./assets/right.jpg');
cards[element].removeEventListener('click',flipCard);
cards[element].style.cursor = 'not-allowed';
});
}
else {
chosenIds.forEach((element)=> {
cards[element].setAttribute('src','./assets/blank.jpg');
});
}
chosenCards = [];
chosenIds = [];
},500);
}
function flipCard() {
const id = this.getAttribute('data-id');
chosenCards.push(imgArray[id].name);
chosenIds.push(id);
this.setAttribute('src',imgArray[id].img);
if(chosenCards.length == 2) {
checkMatch();
}
}