title: How to add event handlers to HTML buttons from within javascript code
body: <p>I have a list of buttons (squares) in HTML like this - </p>
  
  <pre><code>  &lt;td&gt;&lt;button id="18" &gt;&lt;/button&gt;&lt;/td&gt;
    &lt;td&gt;&lt;button id="28" &gt;&lt;/button&gt;&lt;/td&gt;
    &lt;td&gt;&lt;button id="38" &gt;&lt;/button&gt;&lt;/td&gt;
             ...
  </code></pre>
  
  <p>Earlier, for each button, I had to put code within the button tag itself to add an event handler, like this - </p>
  
  <pre><code>  &lt;button id="18" onclick="squareWasClicked(event)"&gt;
  
    function squareWasClicked(event)
     {
        var element = event.target; 
  
        // more code
     }
  </code></pre>
  
  <p>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 - </p>
  
  <pre><code>  function assignEventsToSquares()
     {
       var i,j;
  
       for(i=1;i&lt;=8;i++)
        {
          for(j=1;j&lt;=8;j++)
           {
             var squareID = "" + i + "" + j;
             var square = document.getElementById(squareID);        
             square.onclick = squareWasClicked(); 
           }
        }
     }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>     square.onclick = squareWasClicked(event);
  </code></pre>
  
  <p>event is not detected in the JavaScript code. Please help.  </p>