I have to do a graphical calculator in Javascript, and the problem I have is that I need to press the button to print the result between the previous numbers in the text.
It has occurred to me to do it with a Boolean counter so that only the first click in the operation does not print the result. It works only the first time, since then they begin to concatenate the following numbers that I enter with the previous result.
Is there any easier way to do it?
<fieldset>
<legend>Codigo</legend>
<div id="calculadora">
<div id="texto"></div>
<button id="ce">CE</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="dividir">÷</button>
<button id="siete">7</button>
<button id="ocho">8</button>
<button id="nueve">9</button>
<button id="multiplicar">x</button>
<button id="cuatro">4</button>
<button id="cinco">5</button>
<button id="seis">6</button>
<button id="resta">-</button>
<button id="uno">1</button>
<button id="dos">2</button>
<button id="tres">3</button>
<button id="suma">+</button>
<button id="posneg">+-</button>
<button id="cero">0</button>
<button id="coma">,</button>
<button id="igual">=</button>
</div>
</fieldset>
Javascript
var sacarElemento = document.getElementById.bind(document);
var texto = sacarElemento('texto');
var numero;
var cont = true;
sacarElemento('calculadora').addEventListener('click', function (event) {
var target = event.target;
if (target && target.matches('button')) {
if (!isNaN(target.textContent)) {
texto.textContent = texto.textContent + target.textContent;
} else if (target.textContent == "+") {
if (!cont) {
texto.textContent = parseFloat(numero) + parseFloat(texto.textContent);
} else {
numero = texto.textContent;
texto.textContent = "";
}
cont = false;
}
}
})