JSFiddle - React, Tailwind, and code Playground
by LyndseyB
HTML
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
CSS
.number {
float:left;
margin:10px;
width:80px;
height:80px;
line-height:80px;
border-radius:40px;
font-size:20px;
color:#fff;
text-align:center;
background:#FF8800;
font-weight:bold;
}
.number:nth-child(3n+1) {
clear:left;
}
.win {
background-color:green;
}
.lose {
background-color:red;
}
Babel + JSX
(function() {
let minseconds = 5,
maxseconds = 15,
minspeed = 250,
maxspeed = 1000,
handheld = getDevice(),
evtListener = (handheld) ? 'touchstart' : 'click',
element = document.querySelectorAll('.number');
function random(min,max) {
return Math.floor(Math.random() * (max - min) + min);
}
function getDevice() {
return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? true : false;
}
function countdown(el, num, speed) {
const timer = setInterval(function () {
el.innerText = (num--);
if (num === -1) {
clearInterval(timer);
el.classList.add('lose');
}
// click number
el.addEventListener(evtListener, function () {
let time = this.innerText;
if (time < minseconds) {
this.classList.add('win');
} else {
this.classList.add('lose');
}
clearInterval(timer);
});
}, speed);
}
[].forEach.call(element, function(el) {
let randomNumber = random(minseconds,maxseconds),
speed = random(minspeed,maxspeed);
el.innerText =randomNumber;
countdown(el, randomNumber, speed);
});
})();