Where to put all this jQuery JavaScript code?

From the documentation, I found this example:

We can animate any element, for example a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially shown, we can hide it slowly:

$('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

I remember, 5 years ago, that NEVER ever refer to any element until it is defined. Does this rule still apply? So would I have to put all this code in the footer of my webpage? Or can I put it in a separate file and import it into the footer? What is the best practice?

+5
source share
6 answers

The recommended way to do this is to put all the initialization code in $(document).ready, for example:

$(document).ready(function() {
   $('#foobar').click(function(event) { alert("You Clicked Me!"); });
});
+8

; DOM .

:

  • HTML, .

  • , $(function() { ... }).
    DOM.

+5

SCRIPT HTML ( </body>). :

  • JS (, )
  • JS , HTML- , JS

HTML5, : http://vidasp.net/HTML5-template.html

+2

, . , , dom. , , .

+1

, DOM. , DOM :

$(function() { /* ... your code goes here ... */ }

, , , , .

+1

I asked this question, although in a slightly different way. You might want to take a look at the answers that I also received - they are quite ... philosophical:

Best way to connect GUI objects to events?

0
source

All Articles