Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways of declaring functions in jQuery

Tags:

jquery

I don't understand the difference between the ways of declaring functions on jQuery, and some times I lost some time trying to call a function and it does not work properly because it does not exist in a context. I don't even know if this is different ways of declaring functions on jQuery or if there is other way. Could someone here explain me? I'm totally noob.

    $(function () {
        // Your code
    })

    jQuery(function($) {
        // Your code
    });

    function () {
        // Your code
    }
like image 972
Uder Moreira Avatar asked Nov 29 '22 16:11

Uder Moreira


1 Answers

$(function() { })

...is exactly equivalent to...

$(document).ready(function() {
});

This will fire the function the moment the DOM is ready (DOMReady event).

jQuery(function($) {
});

Is the same thing. In most set-ups, $ := jQuery (only exception is in the case of a NoConflict environment). The first parameter of the closure you're passing to jQuery will return the jQuery object. So, this function simply re-maps $ to jQuery in addition to performing exactly what the other did.

The third statement is a simple function declaration, which has nothing to do with jQuery.

like image 123
Sébastien Renauld Avatar answered Dec 10 '22 23:12

Sébastien Renauld