Why jQuery click doesn't work when included in a separate file

jquery

Solution

You need to have $(function() { ... }) for your click function to work. It tells jquery that the document is loaded and it can start working on the DOM. Before then, the DOM is not ready and your element might not exist.

EDIT: Use this for your external files too, unless you are more advanced and know when NOT to use it.

Problem

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, ``` <html> .... <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script src="scripts/test.js" type="text/javascript"></script> .... <body> <button type="button" class="button" id="my_button">test</button> </body> </html> ``` In 'test.js', I have: ``` $( "#my_button" ).click(function() { alert('test'); return false; }); ``` 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: ``` <html> .... <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $( "#my_button" ).click(function() { alert('test'); return false; }); }); </script> .... <body> <button type="button" class="button" id="my_button">test</button> </body> </html> ``` 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 `$(function() {......}` for it to work? 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? Thank you for your answer.

Original source