JSFiddle - React, Tailwind, and code Playground
by Константин Дралюк
HTML
<div id="app">
<div id="result"></div>
<div id="buttons"></div>
</div>
CSS
body {
margin: 0;
background: #fff;
}
#app {
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
}
button {
background-color: #bbb;
color: #fff;
min-width: 60px;
line-height: 1.5;
padding: 10px 0;
border: 1px solid #fff;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
transition: 0.2s ease;
cursor: pointer;
outline: none;
}
button span {
display: block;
color: #000;
}
button.is-active,
button:hover {
background-color: #4CAF50;
}
button:hover {
background-color: #7ed481;
}
button.is-active:hover {
background-color: #62b965;
}
#result {
font-family: monospace;
font-size: 200px;
line-height: 1;
margin: 0 0 30px;
font-weight: bold;
}
#result span {
display: block;
font-size: .4em;
opacity: .2;
letter-spacing: .136em;
}
JavaScript
const $buttons = document.querySelector('#buttons')
const $result = document.querySelector('#result')
const bits = 8
let result = 0
const bitsMap = []
bitsMap.length = bits + 1
bitsMap.fill(0)
const appendBtn = (value = 0, pow = 0) => {
const $btn = document.createElement('button');
$btn.value = value
$btn.innerHTML = value + `<span>2^${pow}</span>`
$btn.addEventListener('click', e => {
const isActive = $btn.isActive = !$btn.isActive
isActive ? $btn.classList.add('is-active') : $btn.classList.remove('is-active')
isActive ? (result += value) : (result -= value)
bitsMap[pow] = isActive
appendResult()
})
$buttons.append($btn)
}
const appendResult = () => {
$result.innerHTML = result + `<span>${bitsMap.map(s => +s).reverse().join('')}</span>`
}
for (let i = bits; i > 0; i--) {
appendBtn(2 << i - 1, i)
if (i === 1) {
appendBtn(1, 0)
}
}
appendResult()