title: Javascript: Best place to register event handlers
body: <p>This question is so basic, I'm certain in must be a duplicate of <em>something</em>, even though I've <a href="https://stackoverflow.com/search?q=javascript%20where%20event%20handler">looked for something similar</a>.</p>
  
  <p>My question is basically: <strong>Where is the best place to initially register event handlers for HTML elements</strong>?</p>
  
  <p>The easiest way to register an event handler is obviously to just do it inline:</p>
  
  <pre><code>&lt;div id = "mybutton" onclick = "doSomething()"&gt;Click me&lt;/div&gt;
  </code></pre>
  
  <p>But this goes against the overwhelming march towards separation of logic and content in modern web development.  So, in 2012, all logic/behavior is supposed to be done in pure Javascript code.  That's great, and it leads to more maintainable code.  But you still need some initial <em>hook</em> that hooks up your HTML elements with your Javascript code.</p>
  
  <p>Usually, I just do something like:</p>
  
  <pre><code>&lt;body onload = "registerAllEventHandlers()"&gt;
  </code></pre>
  
  <p>But... that's still "cheating", isn't it - because we're still using inline Javascript here.  But what other options do we have?  We can't do it in a <code>&lt;script&gt;</code> tag in the <code>&lt;head&gt;</code> section, because at that point we can't access the DOM since the page hasn't loaded yet:</p>
  
  <pre><code>&lt;head&gt;
  &lt;script type = "text/javascript"&gt;
      var myButton = document.getElementById("mybutton"); // myButton is null!
  &lt;/script&gt;
  &lt;/head&gt;
  </code></pre>
  
  <p>Do we place a <code>&lt;script&gt;</code> tag at the <em>bottom</em> of the page or something?  Like:</p>
  
  <pre><code>&lt;html&gt;
  &lt;body&gt;
  ...
  ...
  &lt;script type = "text/javascript"&gt;
     registerAllEventHandlers();
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>What is the best practice here?</p>