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.
just delay the loading of those scripts? I understand it sort of moves javascript stuff below HTML, but is that a good practice to follow? I want to build good habits as I am beginning to learn it. Habits die hard, as you know. :) Thank you
– user1330974 Jul 11 '13 at 18:36