JSFiddle - React, Tailwind, and code Playground
by zxzc0
HTML
<div class="word" id="word1">-</div>
<div class="bt" id="bt">random</div>
CSS
* {
box-sizing: border-box;
-moz-user-select: none;
user-select: none;
}
body {
background-color: #20262e;
color: white;
font-size: 20px;
}
.word {
padding: 10px;
}
.bt {
width: 80px;
height: 50px;
border: 1px solid white;
display: inline-block;
color: white;
font-size: 20px;
padding-top: 12px;
text-align: center;
cursor: pointer;
}
JavaScript
let arr = [{
q: 'A',
a: 'a'
},
{
q: 'B',
a: 'b'
},
{
q: 'C',
a: 'c'
},
{
q: 'D',
a: 'd'
},
{
q: 'E',
a: 'e'
},
{
q: 'F',
a: 'f'
},
];
const word1 = document.querySelector('#word1');
const bt = document.querySelector('#bt');
function sample (arr) {
let sampledIndexes = [];
const randomIndexGenerator = () => Math.floor(Math.random() * arr.length);
return function randomSelection () {
const randIndex = randomIndexGenerator();
if (arr.length === sampledIndexes.length) {
sampledIndexes = [];
return randomSelection();
} else if (sampledIndexes.includes(randIndex)) {
return randomSelection();
} else {
sampledIndexes.push(randIndex);
return arr[randIndex];
}
}
}
const randomWord = sample(words);
bt.addEventListener("click", randomWord);
randomWord();