I am working on a rock paper scissor game. I'm very new to javascript and only know the basics. The code is a little sloppy. What I want is to be able to continue playing the game after a choice is selected. For example, right now if I click rock, the CPU will randomize a result, but then if I click on paper, the result will stay on the screen and the new result will overlap the old one.
I was thinking of adding another condition to the if statements. Also, I was thinking of adding another function to the return of the if statement that might reset it.
html
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
js
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
function cpuChoice() {
const rand = Math.random()
if (rand < .34) {
cpuPaper.style.display = 'inline-block'
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block'
} else {
cpuScissors.style.display = 'inline-block'
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice))
css
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
position: absolute;
height: 11rem;
}
Firstly, you need to remove position: absolute; for img which was causing the overlapping.
Secondly, each time you call cpuChoice(), you need to hide the previous element before showing the current element.
const userChoice = document.querySelectorAll('.choice')
const cpuScissors = document.querySelector('.cpu-scissors')
const cpuPaper = document.querySelector('.cpu-paper')
const cpuRock = document.querySelector('.cpu-rock')
let currentItem;
function cpuChoice() {
const rand = Math.random();
if (currentItem) {
currentItem.style.display = 'none';
}
if (rand < .34) {
cpuPaper.style.display = 'inline-block';
currentItem = cpuPaper;
} else if (rand >= .67) {
cpuRock.style.display = 'inline-block';
currentItem = cpuRock;
} else {
cpuScissors.style.display = 'inline-block';
currentItem = cpuScissors;
}
}
userChoice.forEach(userChoice =>
userChoice.addEventListener('click', cpuChoice));
.cpu-scissors {
display: none;
}
.cpu-paper {
display: none;
}
.cpu-rock {
display: none;
}
.cpu-result img {
height: 5rem;
}
<div class="main-container">
<div class="score">
<p>You:0</p>
<p>Computer:0</p>
</div>
<div class="user-choice">
<img id="rock" class="choice" src="icons/rock.png">
<img id="paper" class="choice" src="icons/paper.png">
<img id="scissors" class="choice" src="icons/scissors.png">
</div>
<div class="cpu-result">
<img class="cpu-rock" src="icons/rock.png">
<img class="cpu-paper" src="icons/paper.png">
<img class="cpu-scissors" src="icons/scissors.png">
</div>
</div>
You don't need all those IDs and Classes.
Use Indexes!
Using indexes you can also retrieve the winner
See this answer: https://stackoverflow.com/a/53983473/383904
const moves = ["Rock", "Paper", "Scissors"],
messages = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
score = [0, 0, 0], // [PL, AI, draw]
ELS = sel => document.querySelectorAll(sel),
EL_result = ELS("#result")[0],
EL_PLScore = ELS("#PLScore")[0],
EL_AIScore = ELS("#AIScore")[0],
ELS_ai = ELS(".ai");
function game() {
const PL = +this.dataset.user; // Get played index as integer
const AI = ~~(Math.random() * 3); // All you need: 0, 1, 2
const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw
score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
EL_result.innerHTML = `You: ${moves[PL]}, AI: ${moves[AI]}, ${messages[result]}`;
EL_PLScore.textContent = score[0];
EL_AIScore.textContent = score[1];
ELS_ai.forEach(el => el.classList.remove('inline-block')); // Hide all
ELS_ai[AI].classList.add('inline-block'); // Show one
}
// EVENTS:
document.querySelectorAll("[data-user]").forEach(el => el.addEventListener("click", game));
.ai {
display: none;
}
.ai.inline-block {
display: inline-block
}
<div class="main-container">
<div class="score">
<span>You: <span id="PLScore">0</span></span>
<span>Computer: <span id="AIScore">0</span></span>
</div>
<div class="user-choice">
<img data-user="0" src="//placehold.it/50x50/888?text=ROCK">
<img data-user="1" src="//placehold.it/50x50/eee?text=PAPER">
<img data-user="2" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div class="cpu-result">
<img class="ai" src="//placehold.it/50x50/888?text=ROCK">
<img class="ai" src="//placehold.it/50x50/eee?text=PAPER">
<img class="ai" src="//placehold.it/50x50/0bf?text=SCISSORS">
</div>
<div id="result"></div>
</div>
Related
I have been trying to make modal for a custom site I'm building. Everything seemed to go fine. It displayed whichever picture I clicked on and "previous" button works as intended. However, there seems to be a problem with "next" button because it behaves differently depending on which picture I'm currently on. Sometimes it jumps by few indexes forward or even backwards. Some insight would be appreciated. Thanks in advance. Here is a code HTML:
<div id="modalcontainer" class="displaynone">
<h4>
<span id="close">X</span>
</h4>
<img src="" alt="" id="modalcontent">
<div class="buttoncontainer">
<div class="previous">
<span id="prev"><</span>
</div>
<div class="next">
<span id="next">></span>
</div>
</div>
</div>
<div id="imgcontainer">
<img src="images/1.JPG" alt="">
<img src="images/2.JPG" alt="">
<img src="images/3.JPG" alt="">
<img src="images/4.JPG" alt="">
<img src="images/8.png" alt="">
<img src="images/9.jpg" alt="">
<img src="images/10.jpg" alt="">
</div>
And JS:
const modalContainer = document.getElementById("modalcontainer");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
const closeModal = document.getElementById("close");
const modalContent = document.getElementById("modalcontent");
const imgContainer = document.getElementById("imgcontainer");
let containerImages = imgContainer.querySelectorAll("img");
let imgIndex = 0;
containerImages.forEach(function(img){
img.setAttribute("data-index", imgIndex++);
img.addEventListener("click", () => {
if(modalContainer.classList.contains("displaynone")){
modalContainer.classList.remove("displaynone");
modalContainer.classList.add("displaymodal");
modalContent.src = img.src;
};
imgIndex = img.dataset.index;
console.log(imgIndex);
});
});
closeModal.addEventListener("click", () => {
if(modalContainer.classList.contains("displaymodal")){
modalContainer.classList.remove("displaymodal");
modalContainer.classList.add("displaynone");
}
imgIndex = 0;
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % containerImages.length;
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
prevButton.addEventListener("click", () => {
imgIndex = (imgIndex -= 1);
if (imgIndex < 0) {
imgIndex = containerImages.length - 1;
console.log(imgIndex);
};
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
I dummied up some objects to get it to run and your previous/next button code seems to work. It there some other code that might be involved? Something modifying the number of images in the imageContainer?
const prevButton = document.querySelector("#prev");
const nextButton = document.querySelector("#next");
let images = document.querySelectorAll("img");
let imgIndex = 0;
images.forEach((img) =>
img.addEventListener("click", () => {
imgIndex = parseInt(img.dataset.index);
setSelected();
})
);
setSelected();
prevButton.addEventListener("click", () => {
imgIndex = imgIndex -= 1;
if (imgIndex < 0) imgIndex = images.length - 1;
setSelected();
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % images.length;
setSelected();
});
function setSelected() {
images.forEach((img) => img.classList.remove("selected"));
images[imgIndex].classList.add("selected");
}
img {
display: inline-block;
border: 2px solid transparent;
}
.selected {
border: 2px solid red;
}
<div id="imageContainer">
<img src="https://picsum.photos/100?random=1" data-index="0">
<img src="https://picsum.photos/100?random=2" data-index="1">
<img src="https://picsum.photos/100?random=3" data-index="2">
<img src="https://picsum.photos/100?random=4" data-index="3">
</div>
<div>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?
var count = 0;
function promptImg() {
var count1 = document.getElementById(test1)
var count2 = document.getElementById(test2)
var count3 = document.getElementById(test3)
}
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
</div>
<div class="2">
<img id="test2" onclick="promptImg()" src="gerbera.jpg">
</div>
<div class="3">
<img id="test3" onclick="promptImg()" src="gipsofila.jpg">
</div>
</div>
If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.
To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.
const counter = { };
function promptImg(img) {
counter[img.id] = (counter[img.id] || 0) + 1;
console.log(JSON.stringify(counter));
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
Or store the click as a data attribute using dataset.
const counter = { };
const displayClickFrequency = () =>
console.log(JSON.stringify([...document.querySelectorAll('img')]
.reduce((map, img) => ({
...map,
[img.id]: parseInt(img.dataset.clicked, 10) || 0
}), {})));
function promptImg(img) {
const previousValue = parseInt(img.dataset.clicked, 10) || 0;
img.dataset.clicked = previousValue + 1;
displayClickFrequency();
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
You can do it by using an event listener and checking the id of its target element:
document.addEventListener("click", function(element) {
if (element.target.id === "test1") {
//do something
}
});
You can do that with one of there two options:
function promptImg() {
console.log(event.target);
}
[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
img.addEventListener("click", () => {
console.log(event.target)
})
})
img {
width: 100px;
height: 100px;
}
<div class="flowers-with-onclick">
<img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img onclick="promptImg()" src="gerbera.jpg">
<img onclick="promptImg()" src="gipsofila.jpg">
</div>
<div class="flowers-with-eventlistener">
<img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img src="gerbera.jpg">
<img src="gipsofila.jpg">
</div>
If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.
You can test it yourself by using the snippet below and clicking the images. Hope this helped.
var images = document.querySelectorAll(".shared-class");
for (i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this)
})
}
<div>
<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />
</div>
You possibly wat to delegate your clicks to the container - in your case the flowers div
window.addEventListener("load", function() { // on page load
document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
const tgt = e.target;
if (tgt.tagName === "IMG") {
console.log(tgt.id);
}
})
})
img { width: 200px; }
<div id="flowers">
<div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
<div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
<div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>
To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.
Check out MDN's Event Listener page and see the verbose example in the snippet.
// Identifies some elements;
const
flowersContainer = document.getElementById("flowers"),
rosaImg = document.getElementById("rosa-img"),
gerberaImg = document.getElementById("gerbera-img"),
gipsofilaImg = document.getElementById("gipsofila-img"),
countersContainer = document.getElementById("counters");
// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
// for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);
// Defines `handleImageClicks`
function handleImageClicks(event){
// Listeners can access events, which have targets
const clickedThing = event.target;
// Calls `incrementCount` for the selected flower
if(clickedThing == rosaImg){ incrementCount("rosa"); }
else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}
// Defines `incrementCount`
function incrementCount(flowerName){
const
// `.getElementsByClassName` returns a list of elements
// (even though there will be only one element in the list)
listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
myMatchingElement = listOfMatchingElements[0], // First element from list
currentString = myMatchingElement.innerHTML, // HTML values are strings
currentCount = parseInt(currentString), // Converts to number
newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
<div><span id="rosa-img">Picture of rosa</span></div>
<div><span id="gerbera-img">Picture of gerbera</span></div>
<div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
<div>User clicks on rosa: <span class="rosa"></span></div>
<div>User clicks on gerbera: <span class="gerbera"></span></div>
<div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>
In your promptImg function if you use jquery, and you should, inside it add
var idClick=$(this).attr("id");
console.log("This link was clicked"+idClick);
and then you can easily IF it
I am facing this actually I do not understand the actual error is where and which terms I am missing.
I have tried to fix it out, in the console at chrome browser, it locates an error at the started marked line I have given in my snippet.
slide[current].style.display = 'block'; this is actual line I found in the browser getting error
export default function Slider() {
let slide = document.querySelectorAll('.slide');
var current = 0;
function cls(){
for(let i = 0; i < slide.length; i++){
slide[i].style.display = 'none';
}
}
function next(){
cls();
if(current === slide.length-1) current = -1;
current++;
**slide[current].style.display = 'block';**
slide[current].style.opacity = 0.4;
var x = 0.4;
var intX = setInterval(function(){
x+=0.1;
slide[current].style.opacity = x;
if(x >= 1) {
clearInterval(intX);
x = 0.4;
}
}, 100);
}
function prev(){
cls();
if(current === 0) current = slide.length;
current--;
slide[current].style.display = 'block';
slide[current].style.opacity = 0.4;
var x = 0.4;
var intX = setInterval(function(){
x+=0.1;
slide[current].style.opacity = x;
if(x >= 1) {
clearInterval(intX);
x = 0.4;
}
}, 100);
}
function start(){
cls();
slide[current].style.display = 'block';
}
start();
return (
<div>
<div class="container">
<div class="arrow l" onclick="prev()">
<img src={s1.jpg} alt="l" />
</div>
<div class="slide slide-1">
<div class="caption">
<h3>New York</h3>
<p>We love the Big Apple!</p>
</div>
</div>
<div class="slide slide-2">
<div class="caption">
<h3>Los Angeles</h3>
<p>LA is always so much fun!</p>
</div>
</div>
<div class="slide slide-3">
<div class="caption">
<h3>Bahar Dar</h3>
<p>Thank you, Bahar Dar!</p>
</div>
</div>
<div class="arrow r" onclick="next()">
<img src={s2.jpg} alt="r" />
</div>
</div>
</div>
)
}
This is a very simple browser memory game which you need to to flip all the matched cards in order to win.
The bug :
In the game if you click fast enough you can flip more than 2 cards.
I've tried a lot to fix it but couldn't figure it out by myself. I would appreciate any help in solving this issue as I am new to JavaScript and it's still hard for me fix those basic bugs.
Game files:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="css/game.css" />
</head>
<body>
<button class="Change User" onclick="change(this)">Change User</button>
<div class="header">
<img src="img/layout/logo.png">
<h1>Memory Monsters</h1>
<p id="Play Again"></p>
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="1" onclick="cardClicked(this)">
<img src="img/cards/1.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="7" onclick="cardClicked(this)">
<img src="img/cards/7.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<div class="card" data-card="5" onclick="cardClicked(this)">
<img src="img/cards/5.png">
<img class="back" src="img/cards/back.png">
</div>
<script src="js/game.js"></script>
</body>
</html>
javascript:
var getElementsByClassName = prompt ('What is your name?');
window.localStorage.setItem ('name', 'dan');
function change(username) {
prompt('What is your name?');
}
// Those are global variables, they stay alive and reflect the state of the game
var elPreviousCard = null;
var flippedCouplesCount = 0;
// This is a constant that we dont change during the game (we mark those with CAPITAL letters)
var TOTAL_COUPLES_COUNT = 3;
// Load an audio file
var audioWin = new Audio('sound/win.mp3');
// This function is called whenever the user click a card
function cardClicked(elCard) {
// If the user clicked an already flipped card - do nothing and return from the function
if (elCard.classList.contains('flipped')) {
return;
}
// Flip it
elCard.classList.add('flipped');
// This is a first card, only keep it in the global variable
if (elPreviousCard === null) {
elPreviousCard = elCard;
} else {
// get the data-card attribute's value from both cards
var card1 = elPreviousCard.getAttribute('data-card');
var card2 = elCard.getAttribute('data-card');
// No match, schedule to flip them back in 1 second
if (card1 !== card2){
setTimeout(function () {
elCard.classList.remove('flipped');
elPreviousCard.classList.remove('flipped');
elPreviousCard = null;
}, 1000)
} else {
// Yes! a match!
flippedCouplesCount++;
elPreviousCard = null;
// All cards flipped!
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
// and finally add a button to call resetCard()
document.getElementById("Play Again").innerHTML =
'<button onclick="resetCard();">Play Again</button>';
}
}
}
}
function resetCard() {// to erase the flipped classes
var cardclass = document.getElementsByClassName("card");
for (i = 0; i < cardclass.length; i++) {
cardclass[i].classList.remove("flipped");
document.getElementById("Play Again").innerHTML = "";
}
}
CSS:
.header {
background-color: lightblue;
padding: 20px;
border-bottom: 10px solid darkcyan;
color:darkcyan;
font-size: 1.5em;
text-align: center;
}
.header img {
float:right;
}
.card {
background-color: pink;
height: 165px;
width: 165px;
float: left;
margin: 5px;
}
.card img {
position: absolute;
}
.flipped .back {
display: none;
}
i made a game like this. you need to create a variable that starts on 0
let tries = 0;
then add one to it each time a card is selected. make sure to not allow it to count if a card that is already flipped is clicked again. here is some of the code from the function that is run on my onclick. I am using a React framework, but if you write this logic in your JS function, it is what you will need to make it work
selected = (event) => {
if (canClick === true) {
let id = event.currentTarget.id; //card0
let idString = id.toString(); //"card0"
//ONLY ALLOW A CARD TO BE CLICKED IF ITS FACE DOWN
if (this.state[idString] === cardBack) {
idString = idString.replace(/card/g, ''); //"0"
this.setState({[id] : arrayRandom[idString]});
//FIRST PICK
if (counter % 2 == 1) {
curCard1 = arrayRandom[idString].toString();
id1 = id;
counter++;
//SECOND PICK
} else {
//MAKE SURE A CARD DOESN'T GET SELECTED TWICE IN A ROW AND STAY FACE UP
if (id === id1) {
console.log("Select a different card for your second pick");
} else {
counter++;
tries++;
canClick = false; //STOP USER FROM SELECTING ANOTHER CARD
curCard2 = arrayRandom[idString].toString();
id2 = id;
setTimeout(() => {canClick = true}, 1000); //USER CAN PICK AGAIN IN 1 SEONCD
//IF THERE'S A MATCH - CARDS STAY FLIPPED, SCORE INCREASES BY 1
if (curCard1 == curCard2) {
score = score + 1;
//IF THERE'S NO MATCH - CARDS FLIP FACE DOWN AFTER A SECOND
} else {
setTimeout(() => {
this.setState({[id1]: cardBack});
this.setState({[id2]: cardBack});
}, 1000);
}
}
}
} else {
console.log("This card has already been flipped, select another one");
}
}
}
here is my game
https://reactcardmatch.netlify.com/
I need to animate the change of these 3 characters with the data of the array, when I click this blue button on the right.
This is the HTML code I have written so far.
<div class="cards">
<div id="card1" class="card">L</div>
<div id="card2" class="card">A</div>
<div id="card3" class="card">X</div>
<a class="btn btn-flat shuffle" href="#" onclick="travelSurprise();">
</a>
</div>
Javascript code is here.
function travelSurprise() {
let cities = ["NYC", "PTH", "SDN", "KTY", "PRT"];
let card1 = document.getElementById("card1");
let card2 = document.getElementById("card2");
let card3 = document.getElementById("card3");
for (let i = 0; i < cities.length; i++) {
setInterval(function shuffle() {
card1.innerHTML = cities[i].charAt(0);
card2.innerHTML = cities[i].charAt(1);
card3.innerHTML = cities[i].charAt(2);
}, 500);
}
}
I need to change these three letters when I click the button. Animation should be like the 3 letters will change to all the elements of the array for 3,4 seconds and stop at a random position.
Try using setTimeout() instead, where the second argument is the 500ms time multiplied by an index of every array item. For the shuffle, use Fisher-Yates algorithm as described here and just do it every time the a is clicked.
function shuffle(array) {
// shuffle your array code
return array;
}
function travelSurprise(event) {
let cities = ["NYC", "PTH", "SDN", "KTY", "PRT"];
let card1 = document.getElementById("card1");
let card2 = document.getElementById("card2");
let card3 = document.getElementById("card3");
shuffle(cities);
cities.forEach((city, index) => {
setTimeout(() => {
card1.innerHTML = city.charAt(0);
card1.innerHTML = city.charAt(1);
card2.innerHTML = city.charAt(2);
}, (index * 500));
});
}
.cards > div {
display: inline-block;
padding: 2rem;
background: lightblue;
border-radius: .3rem;
}
a {
display: inline-block;
background: #f2f2f2;
width: 1rem;
height: 1rem;
}
<div class="cards">
<div id="card1" class="card">L</div>
<div id="card2" class="card">A</div>
<div id="card3" class="card">X</div>
<a class="btn btn-flat shuffle" href="#" onclick="travelSurprise();">
</a>
</div>