I have checked another questions like this one on stackoverflow, but it doesn't solved my problem.
My problem is that whenever I add events to dynamic added elements. but it doesn't work in case I click on that element. It means that it doesn't work properly.
Here is what I have implemented:
function init() {
let promptMessage = 'Enter the number of rows and columns'
let promptDefault = '1 1';
let prompt = this.prompt(promptMessage, promptDefault);
if (prompt) {
prompt = prompt.split(" ")
console.log(prompt);
prompt[0] = Number(prompt[0]);
prompt[1] = Number(prompt[1]);
return prompt;
}
return init()
}
function selected(i, j) {
return console.log(`You clicked on row ${i} and column ${j}`)
}
var gameSize = init(),
rows = gameSize[0],
cols = gameSize[1],
boardGame = document.querySelector('.board');
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
let div = document.createElement('div');
div.className = `block cell-${i}-${j}`;
div.addEventListener("click", selected(i, j));
boardGame.appendChild(div);
}
}
Problem: I expect that after entering numbers in prompt whenever I inspect the document see onclick="selected(i, j)"
for each of elements. But it doesn't work so. Since the browser render the html file, it console.log all the elements, in case I didn't click on them. Where is the problem?