Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What event does JQuery $function() fire on?

We have a JQuery $(function() statement as:

<script type="text/javascript"> $(function(){   //Code.. }) </script> 

Dumb question - when exactly is this function executed? Is it when the entire HTML page has been downloaded by the client?

What is benefit of using the wrapping your code within $(function() as opposed to just doing:

<script type="text/javascript"> //Code.. </script> 
like image 572
Marcus Leon Avatar asked Oct 11 '10 17:10

Marcus Leon


People also ask

What is jQuery event function?

The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter. click() The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.

What function do we invoke to fire a custom event in jQuery?

trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event. To trigger handlers bound via jQuery without also triggering the native event, use . triggerHandler() instead. alert( param1 + "\n" + param2 );


2 Answers

It fires when the document has been parsed and is ready, and is the equivalent of $(document).ready(function () { }).

The obvious benefit is that having your script tag before other elements on the page means that your script can interact with them even though they're not available at parse time. If you run your script before elements have been parsed and the document is not ready, they will not be available for interaction.

like image 186
Andy E Avatar answered Sep 23 '22 13:09

Andy E


It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.

like image 33
Nrj Avatar answered Sep 24 '22 13:09

Nrj