How you use multiply eventListener for each button in loop?

184 views Asked by At

Im trying to create a calculator that has 10 buttons 0-9 which Im creating in a for loop. Each button needs to have an EventListener to indicate that the user pressed on it. Im trying to figure out why, when clicking on a different button 'add', that has his own listener is the button Im getting directed to wrong function.

This is how I'm creating the 10 buttons :

var count = 0;
function calcolator() {

    //calc div
    var calc_screen = document.createElement("div");
    calc_screen.id = "calc_screen".concat(count.toString());
    calcs_screen.appendChild(calc_screen);

    var result = document.createElement("input");
    result.type = "text";
    result.id = "result".concat(count.toString());
    result.readonly = true;
    result.value = "0";
    calc_screen.appendChild(result);
    for (var i = 0; i <= 9; i++) {
        var numberBtn = document.createElement("BUTTON");
        numberBtn.id = count.toString().concat(i.toString());
        numberBtn.textContent = i.toString();
        numberBtn.value = i.toString();
        numberBtn.addEventListener("click",writeNumberOrOperation(numberBtn.id,result.id));
        calc_screen.appendChild(numberBtn);
    }
    count++;
}

and I have this button that has different EventListener :

//add button
var addCalcBtn = document.createElement("BUTTON");
addCalcBtn.textContent = "Add Calculator for free";
addCalcBtn.addEventListener("click",calcolator);
calcs_screen.appendChild(addCalcBtn);

So when I'm pressing on 'add', in the debugger I see that I'm getting directed to writeNumberOrOperation() function. and when Im pressing on each of 0-9 buttons none of the functions are getting called.

1

There are 1 answers

0
Satpal On BEST ANSWER

You are invoking the method writeNumberOrOperation and binding its return value as event handler.

Use

//Associate result.id using data-* prefix attribute
numberBtn.dataset.resultid = result.id;
//Bind click handler
numberBtn.addEventListener("click",function(){
    writeNumberOrOperation(this.id,this.dataset.resultid);
});

Reference HTMLElement.dataset