Yvonne Marggraf
Yvonne Marggraf

Reputation: 408

How does $(function(){ }); works?

I have the following code:

function example(){
executing_code;

$(function(){
executing_code;
});

(function(){
executing_code;
})();

};

I know, that the third one is a self-invoking function and I know the meaning of the second too, but the third isn't invoking, when I invoke example()... Some days earlier it was the other way round and the second didn't worked. I'm confussed. Now I hope somebody can help me.

Upvotes: 0

Views: 81

Answers (2)

Sim
Sim

Reputation: 3317

$( document ).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {   
  // Handler for .ready() called. 
});`

from https://api.jquery.com/ready/

This Handler is fired, when your page is fully loaded. You need this, when you place a script on top of you html page. The jquery selector don't find an id or a class or a tag when this element isn't loaded yet. So your script in the $(document).ready(function(){}); will be executed after every html element is loaded.

Upvotes: 0

BenG
BenG

Reputation: 15154

$(function() {

is equivalent to

$( document ).ready(function() {

query api here

Meaning it will fire the code inside the $(function() { when the page has finished loading

You need to close the example() before the $(function() { then call it inside.

Upvotes: 1

Related Questions