My idea is to code a calculator with vanila JS, but I came into a problem. I want to solve it by binding keys and add eventlistener to each of them separately. To not repeat my code, I wanted to create a function that would do everything, with me adding just a key number as a parameter. When I run the code, it fires the function immediately, without clicking on "number two" . I know, that the problem is with the "click",getInput(two), I want to make this function work. Any ideas?
let input = document.getElementById("input").innerHTML;
const plus = document.querySelector(".plus");
const minus = document.querySelector(".minus");
const one = document.querySelector(".one");
const two = document.querySelector(".two");
const three = document.querySelector(".three");
const four = document.querySelector(".four");
const five = document.querySelector(".five");
const six = document.querySelector(".six");
const seven = document.querySelector(".seven");
const eight = document.querySelector(".eight");
const nine = document.querySelector(".nine");
const ac = document.querySelector(".ac");
function getInput(number){
console.log("i am here");
console.log(number.textContent);
if (input === 0){
input = number.textContent;
document.getElementById("input").innerHTML = input;
}
else{
input += number.textContent;
document.getElementById("input").innerHTML = input;
}
}
two.addEventListener("click",getInput(two));
ac.addEventListener("click",() =>{
input = 0;
console.log(input);
document.getElementById("input").innerHTML = input;
})
plus.addEventListener("click",() => {
console.log(plus.textContent);
input += plus.textContent;
document.getElementById("input").innerHTML= input;
});
one.addEventListener("click",()=>{
if (input === 0) {
input = one.textContent;
document.getElementById("input").innerHTML=input;
}
else {
input += one.textContent;
document.getElementById("input").innerHTML=input;
}
})
Second question, is there any easier way to detect user's input by not binding each key? (I am new to JS and this would help me a lot)
Kapaak