Currently, I am working on a project where I am using JavaScript to update a calculator's display (.display) based on the numbered button that is clicked.
To achieve this, I am trying to utilize forEach to add a click event listener to each button. This listener will trigger an updateDisplay function which will then update the displayValue variable with the number contained within the div.
Despite my efforts, the code is not functioning as expected and no console errors are being reported. Can anyone offer assistance?
The condensed HTML structure is as follows:
<div class="container">
<div class="sub-container">
<div class="display">
<p id="result-display">
</p>
</div>
<div class="button-grid">
<div class="item" id="7">
<p>
7
</p>
</div>
My JavaScript code can be summarized as follows:
//Define variables for display value and display area, initializing the display.
let displayValue = 0;
let displayArea = document.getElementById('result-display');
displayArea.innerHTML += displayValue;
//Update display based on button clicks
const buttons = document.querySelectorAll('.item');
buttons.forEach(button => {
addEventListener('click', () => {
updateDisplay();
})
});
//Function to update displayValue variable
let updateDisplay = () => {
displayValue = button.innerHTML;
}