Philip007
Philip007

Reputation: 3230

jquery function inside .ready

Could anyone tell me why 'function()' right after .ready is needed to make the script work?

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>

Upvotes: 2

Views: 600

Answers (3)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

function() { } defines an inline function, which is then passed as a parameter to ready().

If you did

$(document).ready($(...).click());

or something similar, the return value of click would be passed to the ready function, which would be something completely different. Of course, the same can be done with named functions:

function initialize() {
    $("button").click(...); // ...
}

$(document).ready(initialize);

Note the lack of () after initialize on the last line, which means "pass this function" instead of "call this function and pass the return value". By the way, just passing a function to $ itself ($(function() { ... });) is a shortcut form for $(document).ready.

Upvotes: 4

Jakub Hampl
Jakub Hampl

Reputation: 40533

$(document).ready means that the code you pass to it won't be called immediately as is normal in javascript but only after stuff was loaded. And one of the two ways you can pass code to a method is via an anonymous function. That is exactly what you are doing.

You could also do it like this:

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

$(document).ready(setup);

This would be using a named function.

Upvotes: 0

Sam Dolan
Sam Dolan

Reputation: 32532

Take a look at the jquery doc on .ready : http://api.jquery.com/ready/

The first argument passed to ready is the callback handler to execute when the dom is ready.

What you're doing is equivalent to this, which may help you understand what's going on a little better:

<script type="text/javascript">
    function on_dom_ready() { 
        $("button").click(function(){
            $("p").hide();
        });
    };
    $(document).ready(on_dom_ready);
  </script>

Upvotes: 0

Related Questions