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


i beginner learning jquery , web development, may dumb question, cannot find answer on google (probably i'm not searching right keywords). have simple html file (say, 'test.html' loads jquery, external javascript file (say, 'test.js') wrote, , have button in it. 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', have:

$( "#my_button" ).click(function() {     alert('test');     return false; }); 

but when click on button, doesn't work. however, when put what's in 'test.js' in 'test.html' 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 explain me why work when insert code in external file , load it? necessary wrap jquery code $(function() {......} work?

ideally, don't want javascript code in html template because it's messy. related/second question is: cleanest/best way separate javascript/jquery code above , yet make work in intended html template?

thank answer.

you need have $(function() { ... }) click function work. tells jquery document loaded , can start working on dom. before then, dom not ready , element might not exist.

edit: use external files too, unless more advanced , know when not use it.


Comments