-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (62 loc) · 2.36 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
const cards = document.querySelectorAll(".card");
let matched = 0;
let cardOne, cardTwo;
let disableDeck = false;
function flipCard({target: clickedCard}) {
if(cardOne !== clickedCard && !disableDeck) {
clickedCard.classList.add("flip");
if(!cardOne) {
return cardOne = clickedCard;
}
cardTwo = clickedCard;
disableDeck = true;
let cardOneImg = cardOne.querySelector(".back-view img").src,
cardTwoImg = cardTwo.querySelector(".back-view img").src;
matchCards(cardOneImg, cardTwoImg);
}
}
function matchCards(img1, img2) {
if (img1 === img2){ //if two cards img matched
matched++; //increment matched value by 1
//if matched value is 8 that means user has matched all the cards (8*2=16 cards)
if(matched == 8) {
setTimeout(() => {
return shuffleCard();
}, 1000);
}
cardOne.removeEventListener("click", flipCard);
cardTwo.removeEventListener("click", flipCard);
cardOne = cardTwo = "";
return disableDeck = false;
}
// if two cards not matched
setTimeout(() => {// adding shake class both card after 400ms
cardOne.classList.add("shake");
cardTwo.classList.add("shake");
}, 400);
setTimeout(() => { // removing both shake and flip calsses from boath card after 1.2 seconds
cardOne.classList.remove("shake", "flip");
cardTwo.classList.remove("shake", "flip");
cardOne = cardTwo = "";//setting both card value to blank
disableDeck = false;
}, 1200);
}
function shuffleCard() {
matched = 0;
disableDeck = false;
cardOne = cardTwo = "";
//creating array of 16 items and each item repeated twice
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
arr.sort(() => Math.random() > 0.5 ? 1 : -1);//sorting array item randomly
//removing flip class from all cards and passing random image to each card
cards.forEach((card, i) => {
card.classList.remove("flip");//when all cards fliped, they turn around(start)
let imgTag = card.querySelector(".back-view img");
imgTag.src = `image/img-${arr[i]}.png`;
card.addEventListener("click", flipCard);
});
}
shuffleCard();
cards.forEach(card =>{ //adding click event to all cards
card.addEventListener('click', flipCard);
});