JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Calculadora</title>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<main>
<span id="box-res"></span>
<div>
<a class="button clear">C</a>
<a class="button plus">+</a>
<a class="button minus">-</a>
<a class="button division">/</a>
</div>
<div>
<a class="button nine">9</a>
<a class="button eight">8</a>
<a class="button seven">7</a>
<a class="button multiply">*</a>
</div>
<div>
<a class="button six">6</a>
<a class="button five">5</a>
<a class="button four">4</a>
<a class="button equal">=</a>
</div>
<div>
<a class="button three">3</a>
<a class="button two">2</a>
<a class="button one">1</a>
<a class="button zero">0</a>
</div>
</main>
<script src="./js/main.js"></script>
</body>
</html>
CSS
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
body{
align-items: center;
background-color: antiquewhite;
display: flex;
font-size: 28px;
height: 100vh;
justify-content: center;
width: 100vw;
}
#box-res{
background-color: #fffaf4;
width: 100%;
}
a{
background-color: #fffaf4;
display: inline-flex;
height: 80px;
justify-content: center;
align-items: center;
margin-top: 12px;
width: 80px;
transition: 0.2s
}
a, span{
border: 2px solid #faead4;
}
a:hover {
cursor: pointer;
background-color: #faebd7;
border: 2px solid black;
box-shadow: 4px 4px black;
transition: 0.2s;
}
span{
align-items: center;
display: flex;
height: 100px;
justify-content: center;
width: 200px;
}
JavaScript
const calculator = () => {
const { btns, res, calc } = helpers();
start(btns, res, calc);
};
const helpers = () => {
return {
btns: document.querySelectorAll(".button"),
res: document.getElementById("box-res"),
calc: []
};
};
const start = (btns, res, calc) => {
btns.forEach(btn => {
btn.addEventListener("click", () => {
if (btn.classList.contains("equal")) {
if (btn.classList.contains("clear")) {
reset(res, calc);
} else {
showResult(res, calc);
}
} else {
if (btn.classList.contains("clear")) {
reset(res, calc);
showCalc(res, calc);
} else {
addNumToCalc(btn, calc);
showCalc(res, calc);
}
}
});
});
};
const reset = (res, calc) => {
if (res) res.textContent = "";
calc.length = 0;
};
const showResult = (res, calc) => {
res.textContent = eval(calc.join(""));
reset(null, calc);
};
const addNumToCalc = (num, calc) => {
calc.push(num.textContent);
};
const showCalc = (res, calc) => {
res.textContent = calc.join("");
};
calculator();