Sorin
Sorin

Reputation: 910

Function does not work when named function is supplied to it

I don't know why these two snippets of code don't produce the same result. In the first example I create a function and pass it and in the second example I write an anonymous function.

 function funct() {
        $("p").slideUp(1000);
 }
 $(document).ready(funct());

 $(document).ready(function() {
        $("p").slideUp(1000);
 });

The second one works, the first one does not. Can somebody tell me why?

Upvotes: 0

Views: 47

Answers (3)

Sumurai8
Sumurai8

Reputation: 20737

To understand why this doesn't work, let's examine what happens when you execute the following code:

$(document).ready(funct());

First funct() is executed. This might or might not return something. If it would to have something like return 1 in it, this would be supplied as argument to $(document).ready( ... ). In this case null or undefined is returned. What you want is to supply the function reference to $(document).ready( ... ) instead. You do this by passing funct to it (much like any other variable).

Similary, having an anonymous function will return the function reference to that anonymous function, which then is used by $(document).ready( ... ).

Upvotes: 2

redmoon7777
redmoon7777

Reputation: 4526

$(document).ready() takes a function as its parameter, so you have to pass a function to it. either do something like this :

function funct() {
     return function() {
           $("p").slideUp(1000);
     }        
 }
 $(document).ready(funct());

Or as the others said, just pass a reference to the function as a parameter like this:

$(document).ready(funct);

Upvotes: 1

jfriend00
jfriend00

Reputation: 707326

When you do this:

$(document).ready(funct());

You are executing funct() immediately and passing it's return value to the .ready() method which is NOT what you want. It is not waiting for the document to be ready before the function executes. What you probably meant to do is this:

$(document).ready(funct);

This way, you are just passing the function reference to the .ready() method and it can then execute the function later rather than immediately and it will then behave identically to the anonymous function example.

To execute a function immediately put parens after it like funct(). To pass a function as a reference that can be called by the function/method you're passing it to, leave off the parens and just pass the name funct.

Upvotes: 5

Related Questions