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.
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.
The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget.
Use element.addEventListener() (originating from the DOM 2 Events spec). In your case it will be
document.getElementById("18").addEventListener("click", squareWasClicked, false);
square.onclick = squareWasClicked();
This calls your click function and assigns the result to your element's event listener, which isn't what you want. Remove the ()
s so that the function itself gets assigned.
Hence, it should look like this
square.onclick = squareWasClicked;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With