Reputation: 85
I'm trying to add a clear button to my calculator. I want it to reset the array to nothing, i.e., storage.length = 0;. However, I can't get my AC key to do anything... I tried getting it to alert 'hi', but nothing. I'm new to this, so I'm lost atm.
/* Click on button and have number saved in array for later use*/
var calcKeys = document.querySelectorAll('.num');
var storage = ['1'];
function addClick(node) {
node.addEventListener('click', function(e) {
storage.push(e.target.innerHTML);
console.log(storage);
if(calcKeys.innerHTML === 'AC') {
alert("hi");
/*storage.length = 0;*/
}
});
}
for (var i = 0; i < calcKeys.length; i++) {
addClick(calcKeys[i]);
}
// when user clicks AC button, clear array
// get node by defining AC key
console.log(storage);
#calculator{
width: 100%;
height: 100%;
background-color: rgba(0, 0, 255, 0.1);
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10px;
}
.keys {
display: flex;
justify-content: space-around;
width: 100%;
flex-wrap: wrap;
max-width: 250px;
}
.keys span {
padding: 20px;
border-radius: 5px;
margin: 8px;
font: bold 20px Arial, sans-serif;
display: flex;
align-items: center;
background-color: grey;
}
.keys span:nth-child(odd) {
background-color: aqua;
}
.screen {
width: 95%;
height: 40px;
border-radius: 3px;
background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<div id="calculator">
<div class="screen"></div>
<div class="keys">
<span class="num">1</span>
<span class="num">2</span>
<span class="num">3</span>
<span class="num">4</span>
<span class="num">5</span>
<span class="num">6</span>
<span class="num">7</span>
<span class="num">8</span>
<span class="num">9</span>
<span class="num">0</span>
<span class="num operator plus">+</span>
<span class="num operator minus">-</span>
<span class="num operator divide">/</span>
<span class="num operator times">*</span>
<span class="num operator ac">AC</span>
</div>
</div>
</head>
<body>
</body>
</html>
Upvotes: 0
Views: 723
Reputation: 422
The problem lies here:
function addClick(node) {
node.addEventListener('click', function(e) {
storage.push(e.target.innerHTML);
console.log(storage);
/* Here */
if(calcKeys.innerHTML === 'AC') {
alert("hi");
/*storage.length = 0;*/
}
});
}
You are buying with calcKeys, not with the current key, so you have to correct for this:
function addClick(node) {
node.addEventListener('click', function(e) {
storage.push(e.target.innerHTML);
console.log(storage);
if(e.target.innerHTML === 'AC') {
alert("hi");
/*storage.length = 0;*/
}
});
}
Upvotes: 1