title: JavaScript: Adding an onClick handler without overwriting the existing one
body: <p>I'm trying to modify all links on a page so they perform some additional work when they are clicked.</p>
  
  <p>A trivial approach might be something like this:</p>
  
  <pre><code>function adaptLinks()
  {
      var links = document.getElementsByTagName('a');
      for(i = 0; i != links.length; i++)
      {
          links[i].onclick = function (e)
          {
              &lt;do some work&gt;
              return true;
          }
      }
  }
  </code></pre>
  
  <p>But some of the links already have an <em>onClick</em> handler that should be preserved. I tried the following:</p>
  
  <pre><code>function adaptLinks()
  {
      var links = document.getElementsByTagName('a');
      for(i = 0; i != links.length; i++)
      {
          var oldOnClick = links[i].onclick;
          links[i].onclick = function (e)
          {
              if(oldOnClick != null &amp;&amp; !oldOnClick())
              {
                  return false;
              }
              &lt;do some work&gt;
              return true;
          }
      }
  }
  </code></pre>
  
  <p>But this doesn't work because <em>oldOnClick</em> is only evaluated when the handler is called (it contains the value of the <strong>last</strong> link as this point).</p>