I have a list of buttons (squares) in HTML like this -
<td><button id="18" ></button></td>
<td><button id="28" ></button></td>
<td><button id="38" ></button></td>
...
Earlier, for each button, I had to put code within the button tag itself to add an event handler, like this:
<button id="18" onclick="squareWasClicked(event)">
function squareWasClicked(event)
{
var element = event.target;
// more code
}
But now I have found out that it is not good practice. So instead, I am trying to add event handlers from within my JavaScript code. But I don't know how to do that. So far, I have tried this:
function assignEventsToSquares()
{
var i,j;
for(i=1;i<=8;i++)
{
for(j=1;j<=8;j++)
{
var squareID = "" + i + "" + j;
var square = document.getElementById(squareID);
square.onclick = squareWasClicked();
}
}
}
But this simply calls the squareWasClicked() function. So how do I add it as an event handler so that the function will be invoked when the square is clicked? Also, how do I say something like:
square.onclick = squareWasClicked(event);
event is not detected in the JavaScript code. Please help.