What does putting a javascript function inside a '$()' do?

113 views Asked by At

I'm learning some AJAX right now and the jQuery function that is being used to submit the form is wrapped inside $( function() { } ) as so. What does this exactly do?

$(function() {
    $('.error').hide();
    $(".button").click(function() {
        // validate and process form here
    }
});
5

There are 5 answers

0
cobbal On BEST ANSWER

This is a shortcut provided by jQuery for running code on page ready. It is equivalent to:

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

jQuery will call this function when the page is ready to be manipulated.

Docs

1
mVChr On

$(function() { }); is short-hand for $(document).ready(function() { });

See documentation.

0
Amir Raminfar On

This is the same thing as $(document).ready(). It just a shortcut to do $(function(){...}) instead of using the ready function.

0
Kimtho6 On

$(function() { }) Waits for the dokument to load before doing enything to the dokument. same as $(document).ready(function() { });

0
Ryan Florence On

As others have stated, it's a shortcut for jQuery(document).ready(fn), which is a cross-browser implementation of document.addEventListener('DOMContentLoaded', fn, useCapture)

https://developer.mozilla.org/en/Gecko-Specific_DOM_Events

Fired at the page's Document object when parsing of the document is finished. By the time this event fires, the page's DOM is ready, but the referenced stylesheets, images, and subframes may not be done loading; use the "load" event to detect a fully-loaded page.