Acubi
Acubi

Reputation: 2783

Why wrap code into 'document ready'

I'm new to Jquery. See an example at http://w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_p. Here, clicking 'Click Me' button the text change. My question is why the following code need to wrapped under $(document).ready(function(){ )}. Otherwise, it doesn't work.

Thanks so much for all your help and really appreciate.

$("button").click(function(){
    $("p").hide();
  });

Upvotes: 2

Views: 1202

Answers (3)

BenM
BenM

Reputation: 53228

Yes, if you didn't wrap this code in the $(document).ready() handler, the objects wouldn't exist because the DOM isn't loaded.

This is a simple test to ensure that the DOM is ready, before invoking methods on its elements.

Upvotes: 2

Nanne
Nanne

Reputation: 64419

If you don't wrap it, it might not find your element. The page needs to be build first, and then you can look for certain elements to add some functions.

So you say "wait for the page to be finished loading, so all elements I want to change are there" before you start adding stuff to them.

Upvotes: 0

PeeHaa
PeeHaa

Reputation: 72682

It makes sure all the DOM elements are loaded before trying to access them

Upvotes: 3

Related Questions