Joseph
Joseph

Reputation: 119867

wrapping a function as a jQuery parameter

i am buliding an autocomplete for my website when i came across this style of building code:

$(function() {

    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $(element).autocomplete(....

    //more code
});

i know about closures, "IIFE"s but this one's a new one for me.

Upvotes: 0

Views: 116

Answers (3)

Starx
Starx

Reputation: 79031

  1. $(function() { }); is equivalent to $(document).ready(function() {}); and as before it executes once the DOM has been ready.

  2. Defining a function inside is to tell that, the function is only available once the dom is ready to execute.

  3. $(element).autocomplete(.... is simply implementing the plugin to the selector, once the DOM is ready to execute.

Hope its clear now :)


$(function() { or $(document).ready(function() { does not need the whole page to load, to run as $(window).load(fn) does.

Upvotes: 2

RvdK
RvdK

Reputation: 19800

Everything in $(function() { } will be executed after the DOM has loaded. I prefer to use $(document).ready(function() { } because it is more clear.

Upvotes: 1

Flo
Flo

Reputation: 1965

$(fn) or $(document).ready(fn) Is jQuery's onload/onDOMContentLoaded handler. The function passed to it is executed once the DOM on the page is ready.

Upvotes: 1

Related Questions