2

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

Rob
  • 14,746
  • 28
  • 47
  • 65

1 Answers1

2

To fire a function with parameter inside event listener you need to create a function in event listener which executes your function with parameter:

btn.addEventListener("click", () => { yourFunction(parameter) });

To unify the event binding you can make something like this:

const numberBtns = document.querySelectorAll(".number-btns");
numberBtns.forEach( btn => btn.addEventListener(....));

and to get which number you pressed you can use dataset or refer to the value of the button:

<button data-number="1" class="number-btns" value="1">
// JS:
btn.dataset.number // = 1
btn.value // = 1
TZiebura
  • 494
  • 3
  • 15