How do I implement a timer to deal each card after 2 seconds? - javascript

I have this function which will deal a card to a player, then to a dealer, then to a player and then to a dealer.
I have tried to use setTimeout(function, milliseconds); but it doesn't work. For example, if I set 2 seconds, it will wait for 4 seconds, then deal the 2 cards to the player and then straight away to dealer 2 cards or it will wait for 8 seconds, then in one batch deal all the cards out.
Here are my methods:
const dealOneCardToPlayer = () => {
// Take a card from the top deck to be assigned to tempcard.
tempCard = deck.cards.splice(0, 1);
//console.log(tempCard);
player.cards.push(tempCard);
if (player.cards.length === 5) {
player.canHit = false;
}
if (player.canHit) {
$("#btnHit").show();
} else {
$("#btnHit").hide();
}
player.handValue = countHandValue(player.cards);
makeCardPlayer(tempCard[0]);
}
const dealOneCardToDealer = (holeCard) => {
// Take a card from the top deck to be assigned to tempcard.
tempCard = deck.cards.splice(0, 1);
dealer.cards.push(tempCard);
if (dealer.cards.length === 5) {
dealer.canHit = false;
}
if (dealer.canHit) {
$("#btnHit").show();
} else {
$("#btnHit").hide();
}
dealer.handValue = countHandValue(dealer.cards);
makeCardDealer(tempCard[0],holeCard);
}
const deal = () => {
debugger;
newDeck();
// Option: to burn first card before deal a card
// to the first player
burnOneCard;
dealOneCardToPlayer();
dealOneCardToDealer(false);
dealOneCardToPlayer();
// true for hole card
dealOneCardToDealer(true);
showGameButtons(true);
checkEndGame1();
checkGameOver();
}
<link href="check.css" rel="stylesheet" />
<style>
body{
font-size: 2em;
}
h3, h5 {
text-align: center;
}
h5{
margin-top:-40px;
}
/*debugging purpose*/
div#oneDeck {
border: 1px solid green;
margin: 10px;
padding: 10px;
}
/*debugging purpose*/
div#playerCards {
border: 1px solid blue;
margin: 10px;
padding: 10px;
}
/*debugging purpose*/
div#dealerCards {
border: 1px solid red;
margin: 10px;
padding: 10px;
}
#mainContainer {
max-width: 600px;
margin: 0 auto;
}
fieldset {
margin-top: 30px;
border: 1px solid #999;
border-radius: 8px;
box-shadow: 0 0 10px #999;
}
legend {
background: #fff;
}
#cardContainerPlayer {
display: flex;
flex-wrap: wrap;
}
.card {
display: inline-block;
vertical-align: top; /*float: left;*/
text-align: center;
margin: 5px;
padding: 10px;
width: 70px;
height: 100px;
font-size: 26px;
background-color: black;
border: solid 1px black;
color: white;
border-radius: 10px;
}
.holeCard {
/*visibility: hidden;*/
border: solid 1px black;
background: repeating-linear-gradient( 45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px );
}
.red {
background-color: red;
border: solid 1px #8C001A;
}
.templatePlayer, .templateDealer {
display: none;
}
#btnGame {
margin: 10px;
}
.winner {
border: solid 5px #7ac142;
}
.btnGame {
background-color: dodgerblue; /* Green */
border: none;
color: white;
padding: 15px 32px;
/*border-radius:10px;*/
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
}
#btnHit {
margin-right: 20px;
}
.flex-container {
padding: 0;
margin: 0;
display: flex;
justify-content: space-between;
max-width: 100%;
overflow: auto;
/*border: 1px solid red*/
}
</style>
<h3>Simple Javascript BlackJack Game</h3>
<h5>developed by Steve Ngai</h5>
<div id="mainContainer">
<div id="btnDevelopment">
<input type='button' value='Create new Deck' onclick='newDeck();' />
<input type='button' value='Burn a card' onclick='burnOneCard();' />
<input type='button' value='Refresh Deck' onclick='showDeck();' />
<input type='button' value='Deal a card to Player' onclick='dealOneCardToPlayer();' />
<input type='button' value='Deal a card to Dealer' onclick='dealOneCardToDealer();' />
<input type='button' value='Show hand value' onclick='showHandValue();' />
<input type='button' value='Check end game' onclick='checkEndGame();' />
<input type='button' value='Refresh deck remaining cards count' onclick='getDeckCardCount();' />
</div>
<fieldset id="deck">
<legend>Remaining cards in the Deck: <span id="deckCardCount"></span></legend>
<div id="oneDeck"></div>
</fieldset>
<fieldset id="containerDealer">
<legend>Dealer (Hand Value: <span id="handValueDealer"></span>)</legend>
<div style="width:30px">
<svg class="checkmarkDealer" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
<path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
</svg>
</div>
<div id="dealerCards"></div>
<div id="cardContainerDealer">
<div class="card templateDealer">
<span class="dealerCardFace"></span>
<span class="dealerCardSuit"></span>
</div>
</div>
<div id="dealerCardsHandValue"></div>
</fieldset>
<div id="btnGame">
<div class="flex-container">
<div class="btn">
<input type='button' class="btnGame" id="btnDeal" value='Deal' onclick='deal();' />
</div>
<div class="btn">
<input type='button' class="btnGame" id="btnHit" value='Hit' onclick='hit();' />
<input type='button' class="btnGame" id="btnStand" value='Stand' onclick='stand();' />
</div>
</div>
</div>
<fieldset id="containerPlayer">
<legend>Player (Hand Value: <span id="handValuePlayer"></span>)</legend>
<div style="width:30px">
<svg class="checkmarkPlayer" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
<path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
</svg>
</div>
<div id="playerCards"></div>
<div id="cardContainerPlayer">
<div class="card templatePlayer">
<span class="playerCardFace"></span>
<span class="playerCardSuit"></span>
</div>
</div>
<div id="playerCardsHandValue"></div>
</fieldset>
<fieldset id="result">
<legend>Game Result</legend>
<div id="gameResult"></div>
</fieldset>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
"use strict";
// Variable/Object declaration and initialization - Start
const isDebug = false;
const DELAY = 2000;
var gameOver = false;
const deck = {
cards: []
}
var tempCard;
const player = {
cards: [],
handValue: 0,
isWinner: false,
canHit: true
}
const dealer = {
cards: [],
handValue: 0,
isWinner: false,
canHit: true
}
var result = document.getElementById("gameResult");
const cardSuit = ["hearts", "diams", "clubs", "spades"];
const cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
$(".checkmarkDealer").hide();
$(".checkmarkPlayer").hide();
$("#handValueDealer").hide();
//Variable/Object declaration and initialization - End
if (!isDebug) {
document.getElementById("btnDevelopment").style.display = "none";
document.getElementById("deck").style.display = "none";
document.getElementById("oneDeck").style.display = "none";
document.getElementById("playerCards").style.display = "none";
document.getElementById("dealerCards").style.display = "none";
//document.getElementById("result").style.display = "none";
} else {
document.getElementById("btnDevelopment").style.display = "block";
document.getElementById("deck").style.display = "block";
document.getElementById("oneDeck").style.display = "block";
document.getElementById("playerCards").style.display = "block";
document.getElementById("dealerCards").style.display = "block";
//document.getElementById("result").style.display = "block";
}
const showGameButtons = (cardDealt) => {
if (cardDealt) {
$("#btnDeal").hide();
$("#btnHit").show();
$("#btnStand").show();
//document.getElementById("btnDeal").disabled = true;
//document.getElementById("btnHit").disabled = false;
//document.getElementById("btnStand").disabled = false;
} else {
$("#btnDeal").show();
$("#btnHit").hide();
$("#btnStand").hide();
//document.getElementById("btnDeal").disabled = false;
//document.getElementById("btnHit").disabled = true;
//document.getElementById("btnStand").disabled = true;
}
if (player.isWinner === true) {
document.getElementById("containerDealer").classList.remove("winner");
document.getElementById("containerPlayer").classList.add("winner");
$("#handValueDealer").show();
$(".checkmarkPlayer").show();
$(".checkmarkDealer").hide();
} else if (dealer.isWinner === true) {
document.getElementById("containerPlayer").classList.remove("winner");
document.getElementById("containerDealer").classList.add("winner");
$("#handValueDealer").show();
$(".checkmarkPlayer").hide();
$(".checkmarkDealer").show();
} else {
}
}
showGameButtons(false);
// In JavaScript, functions are objects.
// You can work with functions as if they were objects.
function card(suit, face) {
this.suit = suit;
this.face = face;
switch (face) {
case "A":
this.faceValue = 11;
break;
case "J":
case "Q":
case "K":
this.faceValue = 10;
break;
default:
this.faceValue = parseInt(face);
break;
}
};
const createDeck = () => {
deck.cards = [];
deck.cards.length = 0;
cardSuit.forEach(function (suit) {
cardFace.forEach(function (face) {
deck.cards.push(new card(suit, face));
});
});
}
const shuffleDeck = () => {
// Fisher–Yates shuffle algorithm
let temp, i, rnd;
for (i = 0; i < deck.cards.length; i++) {
rnd = Math.floor(Math.random() * deck.cards.length);
temp = deck.cards[i];
deck.cards[i] = deck.cards[rnd];
deck.cards[rnd] = temp;
}
}
const newDeck = () => {
createDeck();
shuffleDeck();
document.getElementById("oneDeck").innerHTML = "";
player.cards = [];
player.handValue = 0;
dealer.cards = [];
dealer.handValue = 0;
var myNode = document.getElementById("cardContainerPlayer");
var fc = myNode.firstChild.firstChild;
while (fc) {
myNode.removeChild(fc);
fc = myNode.firstChild;
}
var myNodeDealer = document.getElementById("cardContainerDealer");
var fcDealer = myNodeDealer.firstChild.firstChild;
while (fcDealer) {
myNodeDealer.removeChild(fcDealer);
fcDealer = myNodeDealer.firstChild;
}
document.getElementById("playerCards").innerHTML = "";
document.getElementById("dealerCards").innerHTML = "";
document.getElementById("oneDeck").innerHTML = JSON.stringify(deck);
}
const burnOneCard = () => {
// Remove the top deck to burn
deck.cards.splice(0, 1);
}
const showDeck = () => {
document.getElementById("oneDeck").innerHTML = JSON.stringify(deck);
}
const dealOneCardToPlayer = () => {
return new Promise(function (resolve) {
setTimeout(function () {
// Take a card from the top deck to be assigned to tempcard.
tempCard = deck.cards.splice(0, 1);
//console.log(tempCard);
player.cards.push(tempCard);
if (player.cards.length === 5) {
player.canHit = false;
}
if (player.canHit) {
$("#btnHit").show();
} else {
$("#btnHit").hide();
}
//player.cards.push(new card("Spades","A"));
//player.cards.push(new card("Spades","10"));
document.getElementById("playerCards").innerHTML = JSON.stringify(player);
player.handValue = countHandValue(player.cards);
document.getElementById("handValuePlayer").innerHTML = player.handValue;
makeCardPlayer(tempCard[0]);
resolve();
}, DELAY);
});
}
const dealOneCardToDealer = (holeCard) => {
return new Promise(function (resolve) {
setTimeout(function () {
// Take a card from the top deck to be assigned to tempcard.
tempCard = deck.cards.splice(0, 1);
dealer.cards.push(tempCard);
if (dealer.cards.length === 5) {
dealer.canHit = false;
}
if (dealer.canHit) {
$("#btnHit").show();
} else {
$("#btnHit").hide();
}
document.getElementById("dealerCards").innerHTML = JSON.stringify(dealer);
dealer.handValue = countHandValue(dealer.cards);
document.getElementById("handValueDealer").innerHTML = dealer.handValue;
makeCardDealer(tempCard[0], holeCard);
resolve();
}, DELAY);
});
}
const hasAceInHand = (cardsOnHand) => {
for (let key in cardsOnHand) {
let arr = cardsOnHand[key];
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
for (let prop in obj) {
if (prop === "face") {
if (obj[prop] === "A") {
return true;
}
}
}
}
}
return false;
}
const countHandValue = (cardsOnHand) => {
//console.log(hasAceInHand(cardsOnHand));
let sum = 0;
for (let key in cardsOnHand) {
let arr = cardsOnHand[key];
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
for (let prop in obj) {
if (prop === "faceValue") {
//console.log(prop + " = " + obj[prop]);
sum = sum + obj[prop];
debugger;
if (sum > 21 && hasAceInHand(cardsOnHand)) {
// Transfer Ace's face value from 11 to 1
sum = sum - 11;
sum = sum + 1;
}
}
}
}
}
return sum;
}
const showHandValue = () => {
document.getElementById("playerCardsHandValue").innerHTML = player.handValue;
document.getElementById("dealerCardsHandValue").innerHTML = dealer.handValue;
}
const getDeckCardCount = () => {
document.getElementById("deckCardCount").innerHTML = deck.cards.length;
}
const checkGameOver = () => {
if (gameOver) {
$(".holeCard > :nth-child(1)").show();
$(".holeCard > :nth-child(2)").show();
$(".holeCard").removeClass("holeCard");
$("#handValueDealer").show();
showGameButtons(false);
}
}
const checkEndGame1 = () => {
gameOver = true;
if (player.handValue === 21 && dealer.handValue !== 21) {
result.innerHTML = "BlackJack! Player won.";
player.isWinner = true;
} else if (player.handValue !== 21 && dealer.handValue === 21) {
result.innerHTML = "BlackJack! Dealer won.";
dealer.isWinner = true;
} else if (player.handValue === 21 && dealer.handValue === 21) {
result.innerHTML = "Push.";
} else {
gameOver = false;
}
}
const checkEndGame2 = () => {
if (player.cards.length <= 5 && player.handValue > 21) {
result.innerHTML = "Bust! Dealer won.";
dealer.isWinner = true;
gameOver = true;
}
}
const checkEndGame3 = () => {
if (player.cards.length <= 5 && dealer.cards.length <= 5) {
// Check bust
if (player.handValue <= 21 && dealer.handValue > 21) {
result.innerHTML = "Bust! Player won.";
player.isWinner = true;
} else if (player.handValue === 21 && dealer.handValue !== 21) {
result.innerHTML = "BlackJack! Player won.";
player.isWinner = true;
} else if (player.handValue !== 21 && dealer.handValue === 21) {
result.innerHTML = "BlackJack! Dealer won.";
dealer.isWinner = true;
} else if (player.handValue === dealer.handValue) {
result.innerHTML = "Push.";
} else if (player.handValue > dealer.handValue) {
result.innerHTML = "Player won.";
player.isWinner = true;
} else if (player.handValue < dealer.handValue) {
result.innerHTML = "Dealer won.";
dealer.isWinner = true;
} else {
result.innerHTML = "Error";
}
} else {
result.innerHTML = "Error";
}
gameOver = true;
}
// This function use JQuery lib
function makeCardPlayer(_card) {
// .card is created in the template card css class
var card = $(".card.templatePlayer").clone();
card.removeClass("templatePlayer");
// .cardFace is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".playerCardFace").html(_card.face);
// .suit is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".playerCardSuit").html("&" + _card.suit + ";");
// ♠ -> ♠, ♣ -> ♣, ♥ -> ♥, ♦ -> ♦
// more char, https://www.w3schools.com/charsets/ref_utf_symbols.asp
// hearts and diamonds are red color. otherwise, default black color.
if (_card.suit === "hearts" || _card.suit === "diams") {
card.addClass("red");
}
// option: replace previous card with new card (show one card all the time)
$("#cardContainerPlayer").append(card);
}
// This function use JQuery lib
function makeCardDealer(_card, _holeCard) {
// .card is created in the template card css class
var card = $(".card.templateDealer").clone();
card.removeClass("templateDealer");
// .cardFace is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".dealerCardFace").html(_card.face);
// .suit is created in the template card css class
// It will search for this css class and add the content aka innerHTML
card.find(".dealerCardSuit").html("&" + _card.suit + ";");
// ♠ -> ♠, ♣ -> ♣, ♥ -> ♥, ♦ -> ♦
// more char, https://www.w3schools.com/charsets/ref_utf_symbols.asp
// hearts and diamonds are red color. otherwise, default black color.
if (_card.suit === "hearts" || _card.suit === "diams") {
card.addClass("red");
}
if (_holeCard) {
card.addClass("holeCard");
}
// option: replace previous card with new card (show one card all the time)
$("#cardContainerDealer").append(card);
$(".holeCard > :nth-child(1)").hide();
$(".holeCard > :nth-child(2)").hide();
}
const deal = () => {
debugger;
newDeck();
// Option: to burn first card before deal a card
// to the first player
burnOneCard;
dealOneCardToPlayer()
.then(dealOneCardToDealer)
.then(dealOneCardToPlayer)
.then(dealOneCardToDealer(true));
//dealOneCardToPlayer();
//dealOneCardToDealer(false);
//dealOneCardToPlayer();
//// true for hole card
//dealOneCardToDealer(true);
showGameButtons(true);
checkEndGame1();
checkGameOver();
}
const hit = () => {
dealOneCardToPlayer();
checkEndGame2();
checkGameOver();
}
const stand = () => {
// Recalculate dealer's hand value
//dealer.handValue = countHandValue(dealer.cards);
debugger;
// Simple AI to automate dealer's decision to hit or stand
if (dealer.handValue >= 17) {
checkEndGame3();
} else {
// Hit until dealer's hand value is more than 16
while (dealer.handValue < 17) {
dealOneCardToDealer();
checkEndGame3();
}
}
checkGameOver();
}
</script>

I think the right way to approach is with promises:
const DELAY = 2000;
function dealCardToPlayer() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('Dealing card to player');
resolve();
}, DELAY);
});
}
function dealCardToDealer() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log('Dealing card to dealer');
resolve();
}, DELAY);
});
}
dealCardToPlayer()
.then(dealCardToDealer)
.then(dealCardToPlayer)
.then(dealCardToDealer);

Related

using JS to make tic tac toe

I have made a tic tac toe using JS however it has some problems My code is:
let x = [];
let o = [];
let xTurn = false;
let winPat = [
['00', '10', '20'],
['01', '11', '21'],
['02', '12', '22'],
['00', '01', '02'],
['10', '11', '12'],
['20', '21', '22'],
['00', '11', '22'],
['02', '11', '20']
];
const tableR = document.getElementsByClassName('tableR');
const button = document.getElementById('btn')
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
let newElement = document.createElement('td');
tableR.item(i).appendChild(newElement);
newElement.addEventListener('click', () => {
if (elementIsEmpty(newElement)) {
const img = document.createElement('img');
if (xTurn) {
img.src = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ARed_X.svg&psig=AOvVaw1B-fppvlN2x5oSCGllnXGc&ust=1634565535566000&source=images&cd=vfe&ved=0CAkQjRxqFwoTCMjbg6XN0fMCFQAAAAAdAAAAABAD';
x.push(String(i) + String(j))
} else {
img.src = 'https://www.google.com/imgres?imgurl=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2Fd%2Fd0%2FLetter_o.svg%2F407px-Letter_o.svg.png&imgrefurl=https%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ALetter_o.svg&tbnid=p-B77Lz3DDttwM&vet=12ahUKEwizlYTWzdHzAhXMg9gFHTSaBJkQMygAegUIARDaAQ..i&docid=K2HPZsIMOu4d5M&w=407&h=768&q=pixture%20of%20o&ved=2ahUKEwizlYTWzdHzAhXMg9gFHTSaBJkQMygAegUIARDaAQ';
o.push(String(i) + String(j))
}
newElement.append(img)
checkWinOrDraw(xTurn)
xTurn = !xTurn
}
})
}
}
const td = document.getElementsByTagName('td')
button.addEventListener('click', () => {
reset();
});
function elementIsEmpty(el) {
return (/^(\s| )*$/.test(el.innerHTML));
}
function checkWinOrDraw(xTurn) {
for (let i = 0; i < winPat.length; i++) {
if (xTurn) {
if (winPat[i].every(element => x.includes(element))) {
alert('X wins')
reset()
return
}
} else {
if (winPat[i].every(element => o.includes(element))) {
alert('O wins')
reset()
return
}
}
}
for (let item of td) {
if (elementIsEmpty(item))
return
}
alert('Draw')
reset()
}
function reset() {
x = [];
o = [];
for (let item of td) {
item.textContent = ''
}
}
body {
margin: 0px;
background-color: #3c4552;
color: aliceblue;
text-align: center;
}
header {
height: 75px;
background-color: #1f1e1c;
padding: 20px;
font-size: large;
}
table {
border-collapse: collapse;
margin: 40px auto;
}
td {
border: 7px solid black;
height: 121px;
width: 121px;
cursor: pointer;
}
button {
background-color: #1f1e1c;
color: white;
width: 25%;
height: 50px;
font-size: larger;
border: black solid 2px;
border-radius: 7px;
cursor: pointer;
}
img {
display: block;
width: 100%;
height: 100%;
}
<header>
<h1>TicTacToe</h1>
</header>
<main>
<table>
<tr class="tableR"></tr>
<tr class="tableR"></tr>
<tr class="tableR"></tr>
</table>
</main>
<footer>
<button id="btn">RESET</button>
</footer>
my problem is that when the game ends, say X wins, the image is not rendered on the screen, and alert() is called. I googled a lot and found no solutions.
details and clarity:
the image is not rendered on screen at the end of the game. try on your computer and see. alert() is called before the image is present in-game which results in a bad user experience. hence I need a solution.
Here your append() function is not able to complete image load & your checkWinOrDraw() function got called that's why this is happening.
Please try with the below code i am calling the checkWinOrDraw() once image gets loaded or failed.
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
let newElement = document.createElement('td');
tableR.item(i).appendChild(newElement);
newElement.addEventListener('click', () => {
if (elementIsEmpty(newElement)) {
const img = document.createElement('img');
if (xTurn) {
img.src = 'https://dummyimage.com/20x20/3a4ca6/fff';
x.push(String(i) + String(j))
} else {
img.src = 'https://dummyimage.com/30x30/fff/fff';
o.push(String(i) + String(j))
}
console.log(xTurn)
xTurn = !xTurn
img.addEventListener('load', checkWinOrDraw)
img.addEventListener('error', checkWinOrDraw)
newElement.appendChild(img)
}
})
}
}
function checkWinOrDraw(e,xTurn) {
//console.log('checking',xTurn)
for (let i = 0; i < winPat.length; i++) {
if (xTurn) {
if (winPat[i].every(element => x.includes(element))) {
alert('X wins')
reset()
return
}
} else {
if (winPat[i].every(element => o.includes(element))) {
alert('O wins')
reset()
return
}
}
}
for (let item of td) {
if (elementIsEmpty(item))
return
}
alert('Draw')
reset()
}

How to remove an event listener and add the listener back on another element click

I am creating a simple picture matching game and I will love to make sure when the picture is clicked once, the event listener is removed, this will help me stop the user from clicking on the same image twice to get a win, and then when the user clicks on another element the listener should be added back, I tried doing this with an if statement but the listener is only removed and never added back, I decided to reload the page which somehow makes it look like a solution but I need a better solution that can help me not to reload the page but add the listener back so that the element can be clicked again after the last else if statement run.
here is the sample code below.
//Selecting query elements
const aniSpace = document.querySelector(".container");
const firstCard = document.querySelector("#fstcard");
const secondCard = document.querySelector("#sndcard");
const thirdCard = document.querySelector("#thrdcard");
const playGame = document.querySelector('#play');
const scores = document.querySelector('.scoreboard');
count = 0;
var firstIsClicked = false;
var isCat = false;
var isElephant = false;
var isDog = false;
var isButterfly = false;
var isEmpty = false;
const animatchApp = () => {
const animals = {
cat: {
image: "asset/images/cat.png",
name: "Cat"
},
dog: {
image: "asset/images/puppy.png",
name: "Dog"
},
elephant: {
image: "asset/images/elephant.png",
name: "Elephant"
},
butterfly: {
image: "asset/images/butterfly.png",
name: "butterfly"
}
}
var score = 0;
firstCard.addEventListener('click', function firstBtn() {
var type = animals.cat.name;
if (firstIsClicked === true && isCat === true) {
firstCard.innerHTML = `<img src="${animals.cat.image}">`;
firstCard.classList.add('display');
alert("You won");
score = score + 50;
console.log(score);
document.getElementById('scores').innerHTML = score;
firstIsClicked = false;
isElephant = false;
if (score >= 200){
alert("You are unstoppable, Game won.");
count = 0;
score = 0;
document.getElementById('scores').innerHTML = score;
document.getElementById('attempts').innerHTML = count;
}
firstCard.removeEventListener('click', firstBtn);
} else if (firstIsClicked === false) {
firstCard.innerHTML = `<img src="${animals.cat.image}">`;
firstCard.classList.add('display');
firstIsClicked = true;
isCat = true;
firstCard.removeEventListener('click', firstBtn);
} else if (firstIsClicked === true && isCat != true) {
alert("Not Matched");
count++;
document.getElementById('attempts').innerHTML = count;
firstCard.innerHTML = '';
secondCard.innerHTML = '';
thirdCard.innerHTML = '';
firstCard.classList.remove('display');
secondCard.classList.remove('display');
thirdCard.classList.remove('display');
firstIsClicked = false;
isCat = false;
isDog = false;
isElephant = false;
isButterfly = false;
score = 0;
document.getElementById('scores').innerHTML = score;
location.reload(true);
}
})
secondCard.addEventListener('click', function secondBtn() {
var type = animals.elephant.name;
if (firstIsClicked === true && isElephant === true) {
secondCard.innerHTML = `<img src="${animals.elephant.image}">`;
secondCard.classList.add('display');
alert("You won");
score = score + 50;
console.log(score);
document.getElementById('scores').innerHTML = score;
firstIsClicked = false;
isElephant = false;
if (score >= 200){
alert("You are unstoppable, Game won.");
count = 0;
score = 0;
document.getElementById('scores').innerHTML = score;
document.getElementById('attempts').innerHTML = count;
}
secondCard.removeEventListener('click', secondBtn);
} else if (firstIsClicked === false) {
secondCard.innerHTML = `<img src="${animals.elephant.image}">`;
secondCard.classList.add('display');
firstIsClicked = true;
isElephant = true;
secondCard.removeEventListener('click', secondBtn);
} else if (firstIsClicked === true && isElephant != true) {
alert("Not Matched");
count++;
document.getElementById('attempts').innerHTML = count;
firstCard.innerHTML = '';
secondCard.innerHTML = '';
thirdCard.innerHTML = '';
firstCard.classList.remove('display');
secondCard.classList.remove('display');
thirdCard.classList.remove('display');
firstIsClicked = false;
isCat = false;
isDog = false;
isElephant = false;
isButterfly = false;
score = 0;
document.getElementById('scores').innerHTML = score;
location.reload(true);
}
})
thirdCard.addEventListener('click', function thirdBtn() {
var type = animals.dog.name;
if (firstIsClicked === true && isDog === true) {
thirdCard.innerHTML = `<img src="${animals.dog.image}">`;
thirdCard.classList.add('display');
alert("You won");
score = score + 50;
console.log(score);
document.getElementById('scores').innerHTML = score;
firstIsClicked = false;
isDog = false;
if (score >= 200){
alert("You are unstoppable, Game won.");
count = 0;
score = 0;
document.getElementById('scores').innerHTML = score;
document.getElementById('attempts').innerHTML = count;
}
thirdCard.removeEventListener('click', thirdBtn);
} else if (firstIsClicked === false) {
thirdCard.innerHTML = `<img src="${animals.dog.image}">`;
thirdCard.classList.add('display');
firstIsClicked = true;
isDog = true;
thirdCard.removeEventListener('click', thirdBtn);
} else if (firstIsClicked === true && isDog != true) {
alert("Not Matched");
count++;
document.getElementById('attempts').innerHTML = count;
firstCard.innerHTML = '';
secondCard.innerHTML = '';
thirdCard.innerHTML = '';
firstCard.classList.remove('display');
secondCard.classList.remove('display');
thirdCard.classList.remove('display');
firstIsClicked = false;
isCat = false;
isDog = false;
isElephant = false;
isButterfly = false;
score = 0;
document.getElementById('scores').innerHTML = score;
location.reload(true);
}
})
document.getElementById('attempts').innerHTML = count;
}
animatchApp();
.h1 {
text-align: center;
background-color: azure;
background-image: url("");
}
* {
box-sizing: border-box;
}
.container {
width: 500px;
}
.card1 {
background-color: blue;
float: left;
width: 30%;
padding: 10px;
height: 150px; /* Should be removed. Only for demonstration */
border: 1px solid rgb(179, 177, 177);
transition: transform 0.8s;
transform-style: preserve-3d;
}
.card2 {
background-color: blue;
float: left;
width: 30%;
padding: 10px;
height: 150px; /* Should be removed. Only for demonstration */
border: 1px solid rgb(179, 177, 177);
transition: transform 0.8s;
transform-style: preserve-3d;}
.card3 {
background-color: blue;
float: left;
width: 30%;
padding: 10px;
height: 150px; /* Should be removed. Only for demonstration */
border: 1px solid rgb(179, 177, 177);
transition: transform 0.8s;
transform-style: preserve-3d;
}
.scoreboard {
float: left;
width: 100%;
padding: 10px;
height: 150px; /* Should be removed. Only for demonstration */
}
img {
width: 100%;
height: 100%;
background-color: white;
}
.display {
background-color: white;
transform: rotateY(180deg);
}
<div class="container">
<h1 class="h1">Animatch</h1>
<div class="first">
<div class="card1" id="fstcard"></div>
<div class="card1" id="sndcard"></div>
<div class="card1" id="thrdcard"></div>
</div>
</div>
<div class="scoreboard">
<p>
<button id="play" onclick="animatchApp()">Play</button>
<br>
Score: <span id="scores">0</span>
<br>
Failed attempts: <span id="attempts"></span>
</p>
</div>
you have to define function outside of onclick because you will need this function reference to remove or add it to eventlistener later
see a example below
function onload(){
var main = document.querySelector(".main"),
btns = main.querySelectorAll(".buttons input"),
box = main.querySelector(".box")
btns[0].addEventListener("click",function(){
box.addEventListener("click",functionForEvent)
})
btns[1].addEventListener("click",function(){
box.removeEventListener("click",functionForEvent)
})
function functionForEvent(e){
console.log("clicked")
}
}
onload()
<div class="main">
<div class="box" style="height:120px;width:120px;border:1px solid black;">Click Me</div>
<div class="buttons">
<input type="button" value="Add Event">
<input type="button" value="Remove Event">
</div>
</div>
Here is an example, that shows how to remove the click event from the item clicked and add it to the other items.
It colors the items that can be clicked green, and the item that can't be clicked red.
To keep the example short, it doesn't check, if the elements it operates on, are well defined.
function myonload() {
let elems = document.querySelectorAll('.mydiv');
for(let i = 0; i < elems.length; ++i) {
let elem = elems[i];
elem.addEventListener('click', mydiv_clicked);
}
}
function mydiv_clicked(e) {
let elems = document.querySelectorAll('.mydiv');
for(let i = 0; i < elems.length; ++i) {
let elem = elems[i];
if(elem == e.target) {
elem.removeEventListener('click', mydiv_clicked);
elem.classList.add('mycolor_clicked');
elem.classList.remove('mycolor');
// Do additional logic here
} else {
elem.addEventListener('click', mydiv_clicked);
elem.classList.remove('mycolor_clicked');
elem.classList.add('mycolor');
// Do additional logic here
}
}
}
.mydiv {
height:30px;
width: 200px;
border:1px solid black;
margin-bottom:2px;
}
.mycolor {
background-color:#00ff00;
}
.mycolor_clicked {
background-color:#ff0000;
}
<body onload="myonload()">
<div class="mydiv mycolor">First area</div>
<div class="mydiv mycolor">Second area</div>
<div class="mydiv mycolor">Third area</div>
</body>
The example shown here does not need to check if an event handler already exists, as adding the same event handler twice, replaces the existing one.
You could also add a custom attribute to your elements and toggle it, instead of adding and removing event listeners as shown here and name your attribute data-something, for example data-can-be-clicked.

deal button shouldn't work whilst blackjack dealer bot is running

I have a blackjack challenge which looks like this:
I've programmed a sleep function so that when the bot is playing it can space out its moves over a few seconds rather than all at once. When I click "stand" and the bot is playing I can't click the hit button, but I can click the "deal" button which means everything resets but I don't want the deal button to work while the bot is playing-it should be disabled just like the hit button is.
Anyone know what's going on and why my deal button still works when the bot is playing? Much appreciated.
My sleep function:
function sleep(ms) {
return new Promise( resolve => setTimeout(resolve, ms));
}
The asynchronous dealer logic function:
async function dealerLogic() {
blackjackGame['isStand'] = true;
while (DEALER['score'] < 16 && blackjackGame ['isStand'] === true) {
let card = randomCard();
showCard(card, DEALER);
updateScore(card, DEALER);
showScore(DEALER);
await sleep(1000);
}
if (DEALER['score'] > 15) {
blackjackGame['turnsOver'] = true;
let winner = computeWinner();
showResult(winner);
console.log(['turnsOver']);
}
}
Blackjack deal button function:
function blackjackDeal() {
if (blackjackGame['turnsOver'] === true) {
blackjackGame['isStand'] = false;
let yourImages = document.querySelector('#your-box').querySelectorAll('img');
let dealerImages = document.querySelector('#dealer-box').querySelectorAll('img');
for (i=0; i < yourImages.length; i++) {
yourImages[i].remove();
}
for (i=0; i < dealerImages.length; i++) {
dealerImages[i].remove();}
YOU['score'] = 0;
DEALER['score'] = 0;
document.querySelector('#your-blackjack-result').textContent = 0;
document.querySelector('#your-blackjack-result').style.color = 'white';
document.querySelector('#dealer-blackjack-result').textContent = 0;
document.querySelector('#dealer-blackjack-result').style.color = 'white';
document.querySelector('#blackjack-result').textContent = "Let's play";
document.querySelector('#blackjack-result').style.color = 'black';
blackjackGame['turnsOver'] = true;
}
}
The entire javascript:
//Challenge 5: Blackjack
let blackjackGame = {
'dealer': {'scoreSpan': '#dealer-blackjack-result', 'div': '#dealer-box', 'score': 0},
'you': {'scoreSpan': '#your-blackjack-result', 'div': '#your-box', 'score': 0},
'cards': ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'K', 'J', 'Q', 'A'],
'cardsMap': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'K': 10, 'J': 10, 'Q': 10, 'A': [1, 11]},
'wins': 0,
'losses': 0,
'draws': 0,
'isStand': false,
'turnsOver': true,
};
const YOU = blackjackGame['you']
const DEALER = blackjackGame['dealer']
const hitSound = new Audio('static/sounds/swish.m4a');
const winSound = new Audio('static/sounds/cash.mp3');
const lossSound = new Audio('static/sounds/aww.mp3');
document.querySelector('#blackjack-hit-button').addEventListener('click', blackjackHit);
document.querySelector('#blackjack-stand-button').addEventListener('click', dealerLogic);
document.querySelector('#blackjack-deal-button').addEventListener('click', blackjackDeal);
function blackjackHit() {
if (blackjackGame['isStand'] === false) {
let card = randomCard();
showCard(card, YOU);
updateScore(card, YOU);
showScore(YOU);} }
function randomCard() {
let randomIndex = Math.floor(Math.random() * 13);
return blackjackGame['cards'][randomIndex];
}
function showCard(card, activePlayer) {
if (activePlayer['score'] <= 21) {
let cardImage = document.createElement('img');
cardImage.src = `static/images/${card}.png`;
document.querySelector(activePlayer['div']).appendChild(cardImage);
hitSound.play(); }
}
function blackjackDeal() {
if (blackjackGame['turnsOver'] === true) {
blackjackGame['isStand'] = false;
let yourImages = document.querySelector('#your-box').querySelectorAll('img');
let dealerImages = document.querySelector('#dealer-box').querySelectorAll('img');
for (i=0; i < yourImages.length; i++) {
yourImages[i].remove();
}
for (i=0; i < dealerImages.length; i++) {
dealerImages[i].remove();}
YOU['score'] = 0;
DEALER['score'] = 0;
document.querySelector('#your-blackjack-result').textContent = 0;
document.querySelector('#your-blackjack-result').style.color = 'white';
document.querySelector('#dealer-blackjack-result').textContent = 0;
document.querySelector('#dealer-blackjack-result').style.color = 'white';
document.querySelector('#blackjack-result').textContent = "Let's play";
document.querySelector('#blackjack-result').style.color = 'black';
blackjackGame['turnsOver'] = true;
}
}
function updateScore(card, activePlayer) {
if (card === 'A') {
if (activePlayer['score'] + blackjackGame['cardsMap'][card][1] <= 21) {
activePlayer['score'] += blackjackGame['cardsMap'][card][1];
} else {
activePlayer['score'] += blackjackGame['cardsMap'][card][0];}
} else {
activePlayer['score'] += blackjackGame['cardsMap'][card];
}
}
function showScore(activePlayer) {
if (activePlayer['score'] > 21) {
document.querySelector(activePlayer['scoreSpan']).textContent = 'BUST!';
document.querySelector(activePlayer['scoreSpan']).style.color = 'red';
}
else {
document.querySelector(activePlayer['scoreSpan']).textContent = activePlayer['score'];
}
}
function sleep(ms) {
return new Promise( resolve => setTimeout(resolve, ms));
}
async function dealerLogic() {
blackjackGame['isStand'] = true;
while (DEALER['score'] < 16 && blackjackGame ['isStand'] === true) {
let card = randomCard();
showCard(card, DEALER);
updateScore(card, DEALER);
showScore(DEALER);
await sleep(1000);
}
if (DEALER['score'] > 15) {
blackjackGame['turnsOver'] = true;
let winner = computeWinner();
showResult(winner);
console.log(['turnsOver']);
}
}
function computeWinner() {
let winner;
if (YOU['score'] <= 21) {
if (YOU['score'] > DEALER['score'] || (DEALER)['score'] > 21) {
blackjackGame['wins']++;
winner = YOU;
} else if (YOU['score'] < DEALER['score']) {
blackjackGame['losses']++;
winner = DEALER;
} else if (YOU['score'] === DEALER['score']) {
blackjackGame['draws']++;
}
} else if (YOU['score'] > 21 && DEALER['score'] <= 21) {
blackjackGame['losses']++;
winner = DEALER;
} else if (YOU['score'] > 21 && DEALER['score'] > 21) {
blackjackGame['draws']++;
}
console.log(blackjackGame);
return winner;
}
function showResult(winner) {
let message, messageColor;
if (blackjackGame['turnsOver'] === true) {
if (winner === YOU) {
document.querySelector('#wins').textContent = blackjackGame['wins'];
message = 'You won';
messageColor = 'green';
winSound.play();
} else if (winner === DEALER) {
document.querySelector('#losses').textContent = blackjackGame['losses'];
message = 'You lost';
messageColor = 'red';
lossSound.play();
} else {
document.querySelector('#draws').textContent = blackjackGame['draws'];
message = 'You drew';
messageColor = 'black';
}
document.querySelector('#blackjack-result').textContent = message;
document.querySelector('#blackjack-result').style.color = messageColor;
}
}
The HTML:
<div class="container-5">
<h2>Blackjack Challenge</h2>
<h3><span id="blackjack-result">Let's Play</span></h3>
<div class="flex-blackjack-row-1">
<div id="your-box">
<h2>You: <span id="your-blackjack-result">0</span></h2>
</div>
<div id="dealer-box">
<h2>Dealer: <span id="dealer-blackjack-result">0</span></h2>
</div>
</div>
<div class="flex-blackjack-row-2">
<button class="btn-lg btn-primary mr-2" id="blackjack-hit-button">Hit</button>
<button class="btn-lg btn-warning mr-2" id="blackjack-stand-button">Stand</button>
<button class="btn-lg btn-danger mr-2" id="blackjack-deal-button">Deal</button>
</div>
<div class="flex-blackjack-row-3">
<table>
<tr>
<th>Wins</th>
<th>Losses</th>
<th>Draws</th>
</tr>
<tr>
<td><span id="wins">0</span></td>
<td><span id="losses">0</span></td>
<td><span id="draws">0</span></td>
</tr>
</table>
</div>
</div>
<script src ="static/script.js">
</script>
</body>
</html>
The CSS:
.container-5 {
width: 75%;
margin: 0 auto;
text-align: center;
border: 1px solid black;
}
.flex-blackjack-row-1, .flex-blackjack-row-2
{
display: flex;
border: 1px solid black;
padding: 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-around;
color: #ffffff;
background: url('https://image.freepik.com/free-vector/poker-table-background-green-color_47243-1068.jpg') center;}
.flex-blackjack-row-3 {
display: flex;
border: 1px solid black;
padding: 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-around;
}
.flex-blackjack-row-1 div {
border: 1px solid black;
padding: 10px;
height: 350px;
text-align: center;
flex: 1;
}
.flex-blackjack-row-1 img {
width: 25%;
padding: 10px;
}
.flex-blackjack-row-2 button {
border: 1px solid black;
padding: 10px;
}
.flex-blackjack-row-2 div {
border: 1px solid black;
padding: 10px;
}
table, th, td {
padding: 5px;
border: 1px solid black;
}
.flex-blackjack-row-2 {
display: flex;
border: 1px solid black;
padding: 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-around;
}

CSS Transition not working with Javascript on web component

i'm new on Javascript and i'm trying to create a web component, precisely some kind of list view. The goal would be it can expand and collapse when I click an item, and I'd like it to do with transitions.
I already put the transition on the template, but for some reason, it doesn't work, just grow or collapse instantly without the animation.
Rarely, if I do a const listView = document.querySelector(".list-view") and then listView.collapse() it works.
The summary code is:
class ListItem extends HTMLElement {
constructor(items = []) {
super();
//Template and its variables
const listItemTemplate = document.createElement("template");
listItemTemplate.innerHTML = `
<style>
.listitem{
//some other properties
transition: height 0.3s cubic-bezier(0.65, 0, 0.35, 1);
height: ${this.initialHeight};
}
//Other styles...
</style>
changedItem(itemSelected){
//More stuff
this.refreshDOMItems();
this.collsapse();
}
`;
expand() {
let height = 10;
Array.from(this.itemsHTML).forEach((item) => {
height += item.clientHeight;
});
this.listItem.style.height = height / 16 + "rem";
}
collapse() {
this.listItem.style.height = this.initialHeight;
}
Edit: Here is a Codepen.
https://codepen.io/salvabarg/pen/zYqJNMj
What i am doing wrong? Hope the code is not much caotic. Thank you in advance!
You are overriding the height transition with transition: background .5s ease; on .listitem:hover, so removing this line solves the problem:
.listitem:hover{
/*transition: background .5s ease;*/
background: rgba(255,255,255,.65);
}
class ListItem extends HTMLElement {
constructor(items = []) {
super();
//Template and its variables
this.initialHeight = "3.75rem";
this.initialBorderRadius = stringToNumber(this.initialHeight) / 2 + "rem";
const listItemTemplate = document.createElement("template");
listItemTemplate.innerHTML = `
<style>
ul{
box-sizing: border-box;
margin: 0px;
padding: 0px;
list-style: none;
}
.ul{
display: flex;
align-items: center;
flex-direction: column;
height: 3.75rem;
}
.listitem{
font-family: 'Nunito', sans-serif;
display: inline-block;
overflow: hidden;
box-sizing: border-box;
background-color: white;
border-radius: ${this.initialBorderRadius};
padding: 0px 1rem;
cursor: pointer;
box-shadow: 0px 0px 1.25rem rgba(4,25,106,.14);
transition: height 0.3s cubic-bezier(0.65, 0, 0.35, 1);
height: ${this.initialHeight};
}
li.item{
box-sizing: border-box;
min-height: ${this.initialHeight};
display: flex;
align-items: center;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
.img{
width: 2rem;
margin-right: 0.625rem;
border-radius: 50%;
}
.name{
font-size: 1.125rem;
font-weight: 700;
color: var(--autores);
margin-right: 0.6rem;
}
.listitem:hover{
/*transition: background .5s ease;*/
background: rgba(255,255,255,.65);
}</style>
<div class="listitem">
<ul class="ul">
</ul>
</div>
`;
//Constructor
this.attachShadow({
mode: "open"
});
this.shadowRoot.appendChild(listItemTemplate.content.cloneNode(true));
this.items = items;
this.listItem = this.shadowRoot.querySelector(".listitem");
this.itemsHTML = this.shadowRoot
.querySelector(".listitem")
.querySelector(".ul").children;
const ul = this.shadowRoot.querySelector(".listitem").querySelector(".ul");
this.ul = ul;
}
connectedCallback() {
//Do
//Carga de items por defecto
const item = {
name: "Item",
avatar: "images/users.svg",
selected: false
};
const item_two = {
name: "Item 2",
avatar: "images/users.svg",
selected: false
};
const item_three = {
name: "Item 3",
avatar: "images/users.svg",
selected: false
};
this.addItem(item);
this.addItem(item_two);
this.addItem(item_three);
this.refreshDOMItems();
//event listeners for each item;
const itemClick = this.shadowRoot.querySelector(".listitem");
itemClick.addEventListener("click", (event) => {
event.preventDefault();
let targetStr = "";
const trgtCls = event.target.classList;
if (
trgtCls.contains("name") ||
trgtCls.contains("img") ||
trgtCls.contains("item")
) {
if (trgtCls.contains("name")) {
targetStr = event.target.innerText;
}
if (trgtCls.contains("img")) {
targetStr = event.target.nextElementSibling.innerText;
}
if (trgtCls.contains("item")) {
targetStr = event.target.querySelector(".name").innerText;
}
}
if (targetStr === this.items[0].name) {
this.expand();
} else {
this.changedItem(targetStr);
}
});
}
addItem(item = Object) {
this.items.push(item);
this.items.forEach((item) => {
item.selected = false;
});
this.items[0].selected = true;
console.log(item.selected);
}
refreshDOMItems() {
removeChildNodes(this.ul);
this.items.forEach((item) => {
const itemTemplate = document.createElement("template");
itemTemplate.innerHTML = `
<li class="item">
<svg viewBox="0 0 512 512" width="100" title="user-alt" class="img">
<path d="M256 288c79.5 0 144-64.5 144-144S335.5 0 256 0 112 64.5 112 144s64.5 144 144 144zm128 32h-55.1c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16H128C57.3 320 0 377.3 0 448v16c0 26.5 21.5 48 48 48h416c26.5 0 48-21.5 48-48v-16c0-70.7-57.3-128-128-128z" />
</svg>
<p class="name">${item.name}</p>
</li>
`;
this.ul.appendChild(itemTemplate.content.cloneNode(true));
});
}
getItems() {
return this.items;
}
changedItem(itemSelected) {
let arr = Array.from(this.items);
this.items.forEach(function(item, index) {
if (item.name == itemSelected) {
arr = moveElementArray(arr, index, 0);
}
});
this.items = arr;
this.items.forEach((item) => {
item.selected = false;
});
this.items[0].selected = true;
this.refreshDOMItems();
this.collapse();
}
selected() {
let selected;
this.items.forEach((item) => {
if (item.selected === true) {
selected = item;
}
});
return selected;
}
value() {
let selected;
this.items.forEach((item) => {
if (item.selected === true) {
selected = item;
}
});
return selected.name;
}
expand() {
let height = 10;
Array.from(this.itemsHTML).forEach((item) => {
height += item.clientHeight;
});
this.listItem.style.height = height / 16 + "rem";
}
collapse() {
this.listItem.style.height = this.initialHeight;
}
}
window.customElements.define("c-list-item", ListItem);
const lsim = document.querySelector(".list");
function removeChildNodes(element = HTMLElement) {
while (element.childElementCount > 0) {
element.removeChild(element.firstChild);
}
}
function stringToNumber(string = String) {
let newNumber = "";
let afterComma = "";
let comma = false;
Array.from(string).forEach((char) => {
if (char === "." || char === ",") {
comma = true;
}
if (comma === false) {
if (Number(char)) {
newNumber += Number(char);
}
} else {
if (Number(char)) {
afterComma += Number(char);
}
}
});
if (afterComma != "") {
newNumber += "." + afterComma;
}
return Number(newNumber);
}
function moveElementArray(array = Array, from = Number, to = Number) {
const fromArr = array[from];
if (from > to) {
for (let index = from; index >= to; index--) {
array[index] = array[index - 1];
if (index == to) {
array[index] = fromArr;
}
}
} else {
for (let index = from; index <= to; index++) {
array[index] = array[index + 1];
if (index == to) {
array[index] = fromArr;
}
}
}
return array;
}
function replaceElementArray(array = Array, from = Number, to = Number) {
const fromArr = array[from];
const toArr = array[to];
array[from] = toArr;
array[to] = fromArr;
return array;
}
<body style="background-color: #f0f0f0;">
<c-list-item class="list"></c-list-item>
</body>

How to make a reset button appear after certain requirements?

So, i want a reset button to appear on my page when the score of the player reaches 5. But i can't seem to make it appear.
if (Score == 5) {
btnQuestion.disabled = true;
txtQuestionFeedback.innerText = "Correct! \n Congratulations, you've got 5 stars!";
imgScore5.src = "Images/StarOn.gif";
document.getElementById(btnReset).innerHTML = btnReset;
}
Try the following:
1) Insert your button element inside a DIV like this for easier reading
<div id="resetButtonDiv">
<button id="resetButton"></button> <!-- here goes your button config -->
</div>
2) Change the style like this using JS
<script>
function showResetButton() {
document.getElementById("resetButton").style.display = "none";
if (Score == 5) {
// Replace "Score" with your variable or element
document.getElementById("resetButton").style.display = "show";
}
}
showResetButton()
</script>
This was my way to do it:
ScoreBoard = function(sId, sIntoNode = '', fnOnChange = null) {
this.m_sId = sId != '' ? sId : 'scoreboard';
this.m_iScore = 0;
this.m_fnOnChange = fnOnChange;
if(sIntoNode != '') {
let TargetNode = document.getElementById(sIntoNode);
if(TargetNode) {
TargetNode.innerHTML = TargetNode.innerHTML + '<div class="scoreboard-score" id="' + this.m_sId + '">0</div>';
}
}
}
ScoreBoard.prototype.SetScore = function(iNewScore) {
this.m_iScore = iNewScore;
let scoreBoard = document.getElementById(this.m_sId);
if(scoreBoard) {
scoreBoard.innerHTML = this.m_iScore;
}
if(this.m_fnOnChange && typeof this.m_fnOnChange == 'function') {
this.m_fnOnChange(this);
}
}
ScoreBoard.prototype.AddScore = function(iAmount) {
this.SetScore(this.m_iScore + iAmount);
}
ScoreBoard.prototype.Reset = function() {
this.SetScore(0);
}
ScoreBoard.prototype.GetScore = function() {
return this.m_iScore;
}
function OnScoreChange(target) {
let resetBtn = document.getElementById('myScore-reset');
if(resetBtn) {
if(target.GetScore() >= 5) {
resetBtn.style.display = "block";
} else {
resetBtn.style.display = "none";
}
}
}
var myScore = new ScoreBoard('myScore', 'score', OnScoreChange);
var i = 0;
function test() {
myScore.AddScore(1);
i++;
if(i < 20) setTimeout(test, 1000);
}
test();
div#score {
padding: 12px;
background-color: darkgrey;
font-family: Arial;
border-radius: 12px;
box-shadow: 0 0 12px 3px black;
}
div.score-head {
background-color: black;
color: white;
padding: 6px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
div.scoreboard-score {
background-color: #EAEAEA;
padding: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
div#score button {
display: none;
}
<div id="score">
<button onClick="myScore.Reset();" id="myScore-reset">Reset Score</button>
<div class="score-head">Score:</div>
</div>
I've sorted it guys!
Instead, i just used a visibility attribute on the button to hide it on page startup. And then called on that attribute in a Function for HideButton().
```
function ShowResetButton() {
document.getElementById("btnReset").style.visibility = "visible";
}
```
But thank you all for your input! i really appreciate it!
Take it easy,
Happy coding!

Categories