title: How to change onClick handler dynamically?
body: <p>I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something. </p>
  
  <p>I have a simple script where I want to set the onClick handler for an <code>&lt;A&gt;</code> link on initialization of the page.</p>
  
  <p>When I run this I <strong>immediately</strong> get a 'foo' alert box where I expected to only get an alert when I click on the link.</p>
  
  <p>What stupid thing am I doing wrong? (I've tried click= and onClick=)...</p>
  
  <pre><code>&lt;script language="javascript"&gt;
  
      function init(){
  
          document.getElementById("foo").click = new function() { alert('foo'); };
      }
  
  &lt;/script&gt;
  
  &lt;body onload="init()"&gt;
      &lt;a id="foo" href=#&gt;Click to run foo&lt;/a&gt;
  &lt;/body&gt;
  </code></pre>
  
  <hr>
  
  <p><strong>Edit:</strong> I changed my accepted answer to a jQuery answer. The answer by '<a href="https://stackoverflow.com/questions/249074/how-to-change-onclick-handler-dynamically/249093#249093">Már Örlygsson</a>' is technically the correct answer to my original question (<code>click</code> should be <code>onclick</code> and <code>new</code> should be removed) but I <strong>strongly discourage</strong> anyone from using 'document.getElementById(...) directly in their code - and to use <a href="http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery" rel="noreferrer">jQuery</a> instead.</p>