I am doing some exercises in javascript with closures, and I have played around with this example, where I was supposed to create buttons and the on clicking them alert their number:
function addButtons(numButtons) {
for (var i = 0; i < numButtons; i++) {
var button = document.createElement('input');
button.type = 'button';
button.value = 'Button ' + (i + 1);
button.onclick = function() {
alert('Button ' + (i + 1) + ' clicked');
}(i);
document.body.appendChild(button);
document.body.appendChild(document.createElement('br'));
}
};
addButtons(5);
But, on page load, script is alerting button numbers even before they were created, why is that so? I have tried with swaping the onclick method for addEventListener like so:
button.addEventListener("click", function () {
alert('Button ' + (i + 1) + ' clicked');
}(i));
But the result was the same.