This is a critical point to "get" to use Javascript effectively. The
line
  $('.poem-stanza').addClass('emphasized');
by itself is executed as soon as the interpreter gets to it.

  function(){ $('.poem-stanza').addClass('emphasized'); }
doesn't execute the addClass; it just creates a function that can be
executed later It's just like writing, somewhere else
in your code:

  function someFunction() { $('.poem-
stanza').addClass('emphasized'); }

except that the first function doesn't have a name (it's "anonymous").
It still can be assigned to a variable or passed as
an argument.

So:
 $(document).ready(function() {
   $('.poem-stanza').addClass('emphasized');
 });
creates an anonymous function and passes it to the $(document).ready
function, and $(document).ready keeps the reference to that function
around until the document is in fact ready, then executes it.

But:
 $(document).ready(
   $('.poem-stanza').addClass('emphasized');
 );

does the $('.poem-stanza').addClass('emphasized'); immediately: it
finds all elements with class 'poem-stanza' which probably is nothing
since your script element is probably in the head, before any of the
body elements have been created, adds the class to whatever it found
and passes those elements (not a function!) to $(document).ready.
$(document).ready expects to get a function, not a jQuery object of
HTML elements, and will probably throw an error.

I think Javascript 2 will have a more elegant way of expressing "a
block of code to be stored and executed later" but for now we have to
use function(){...}

HTH,
Danny

On Feb 5, 9:30 am, Pickledegg <[EMAIL PROTECTED]> wrote:
> I'm reading 'learning jQuery'. In this example, and in fact every
> example, why do you pass a function as an argument.
>
> $(document).ready(function() {
> $('.poem-stanza').addClass('emphasized');
>
> });
>
> why can't I do this?
>
> $(document).ready(
> $('.poem-stanza').addClass('emphasized');
> );
>
> Thanks. I'm asking this a learning exercise, so I apologize in advance
> for the apparent stupidity of it.

Reply via email to