My HTML code consists of a series of square buttons like this -
<td><button id="18" ></button></td>
<td><button id="28" ></button></td>
<td><button id="38" ></button></td>
...
In the past, I used to add event handlers directly within each button tag, like so:
<button id="18" onclick="squareWasClicked(event)">
function squareWasClicked(event)
{
var element = event.target;
// more code
}
However, I have learned that this approach is not recommended. Instead, I am now attempting to assign event handlers in my JavaScript code. But I am facing some challenges with this new method. Here is what I have tried:
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();
}
}
}
Unfortunately, this approach simply calls the squareWasClicked()
function. Can someone guide me on how to properly set it as an event handler so that the function gets executed when the square is clicked? Also, I am struggling with passing the event parameter correctly, as shown below:
square.onclick = squareWasClicked(event);
The JavaScript code seems unable to detect the event parameter. Any assistance would be greatly appreciated.