March 8, 2012

wrapping a function as a jQuery parameter

Question by Joseph the Dreamer

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.

  • what’s with the “jQuery-wrapped” code above?
  • is there any particular reason i should do that? (scope?)
  • optimization-wise, should i even do it that way?

Answer by Starx

  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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!