I have made a calculator using JS, the number pad elements with the values from 1-9 are triggered using an event listener.
const items = document.querySelectorAll('.item-number');
These display on my screen element
let display = document.getElementById('show');
These all work fine, my issue is with the decimal point button, in which I originally tried to assign an event listener. This worked fine if i press the decimal button and then press a number button
eg; 0.2 but when i press number first then decimal i get the same as above.
I'm fairly new to JS and have tried many different ways to try and solve this, such as using concat etc
const itemDecimal = document.querySelector('.item-operator__decimal');
const itemNumbers = document.querySelectorAll('.item-number');
const itemDecimal = document.querySelector('.item-operator__decimal');
const itemClear = document.querySelector('.item-clear__recent');
const itemClearAll = document.querySelector('.item-clear__all');
let display = document.getElementById('show');
let outPutTextElements;
itemNumbers.forEach(item => {
let itemTxtNumbers = [item.innerHTML]; // get string numbers 1-9 values
item.addEventListener('click',function(){
outPutTextElements=
document.getElementById('show').innerHTML += itemTxtNumbers; // display incremented element
let number = parseFloat(outPutTextElements); // prevent zero from appending to front
number % 1 == 0 ? number.toFixed(0): number.toFixed(1);
document.getElementById('show').innerHTML = number;
});
});
itemDecimal.addEventListener('click',function(decimal){
let decimalPoint = decimal.target.innerText;
display.innerText = decimalPoint;
})
Below is the html
<div class="screen" id="show">
<button class="item item-number">7</button>
<button class="item item-number">8</button>
<button class="item item-number">9</button>
<button class="item item-clear__recent">CE</button>
<div class="item item-clear__all">C</div>
<button class="item item-number">4</button>
<button class="item item-number">5</button>
<button class="item item-number">6</button>
<button class="item item-operator">/</button>
<button class="item item-operator">*</button>
<button class="item item-number">1</button>
<button class="item item-number">2</button>
<button class="item item-number">3</button>
<button class="item item-operator">-</button>
<button class="item item-operator">+</button>
<button class="item item-number item-number__zero">0</button>
<button class="item item-operator__decimal">.</button>
<button class="item item-operator__equals">=</button>
</div>