title: Why jQuery click doesn't work when included in a separate file
body: <p>I am a beginner learning jQuery and web development, so this may be a dumb question, but I cannot find an answer to this on Google (probably I'm not searching for the right keywords). I have a simple HTML file (say, 'test.html' that loads jQuery, an external javascript file (say, 'test.js') that I wrote, and have a button in it. For example,</p>
  
  <pre><code>&lt;html&gt;
  ....
  &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script src="scripts/test.js" type="text/javascript"&gt;&lt;/script&gt;
  ....
  &lt;body&gt;
  &lt;button type="button" class="button" id="my_button"&gt;test&lt;/button&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>In 'test.js', I have:</p>
  
  <pre><code>$( "#my_button" ).click(function() {
      alert('test');
      return false;
  });
  </code></pre>
  
  <p>But when I click on the button, it doesn't work. However, when I put what's in 'test.js' in 'test.html' like this:</p>
  
  <pre><code>&lt;html&gt;
  ....
  &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
  $(function() {
      $( "#my_button" ).click(function() {
          alert('test');
          return false;
      });
  });
  &lt;/script&gt;
  ....
  &lt;body&gt;
  &lt;button type="button" class="button" id="my_button"&gt;test&lt;/button&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>It works. First question is: Can someone explain me why it would work when I insert the code in external file and load it? Is that always necessary to wrap jQuery code with <code>$(function() {......}</code> for it to work?</p>
  
  <p>Ideally, I don't want javascript code in my HTML template because it's obviously messy. Related/second question is: What is the cleanest/best way to separate the javascript/jQuery code like above and yet make it work in the intended HTML template? </p>
  
  <p>Thank you for your answer.</p>