I am trying to make a simple web app, it is a remote control numpad that when I press a key it shows that number in the corresponding div element. Before I wrote the submitted code I tried the following:
for(var i=1;i<btnNumber.length;i++){
btnNumber[i].addEventListener("click", function(){
dvNumber[i].textContent=this.textContent;
})
}
It didn’t work and after I did some research and reading many post here I vaguely understand why; something to do with the asynchronous nature of Javascript and variable state preservation (It will be great if someone can give a clear explanation).
Now the below code almost worked with the following console error:
“Uncaught TypeError: Cannot read property 'addEventListener' of undefined”
Also the button with no. 1 is not working.
What exactly is happening, can anyone give a beginner level explanation.
var btnNumber=document.querySelectorAll("button")
var dvNumber=document.querySelectorAll("div")
for(let i=1;i<=btnNumber.length;i++){
btnNumber[i].addEventListener("click", function(){
writeDiv(i,this)
})
}
function writeDiv(i,obj){
dvNumber[i].textContent=obj.textContent;
}
div{
width:200px;
height: 200px;
float: left;
border: 4px solid gray;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="testingpagelayout.css">
<title>Document</title>
</head>
<body>
<button >1</button>
<button >2</button>
<button >3</button>
<br>
<button >4</button>
<button >5</button>
<button >6</button>
<br>
<button >7</button>
<button >8</button>
<button >9</button>
<br>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script src="testingpagelayout.js"></script>
</body>
</html>