Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ready function aliases

I'm a little confused about all the different ways to create a new jQuery object.

the relevent docs seem to be: http://api.jquery.com/ready/ http://api.jquery.com/jQuery/

From those two docs the following are all equivalent, (with the exception of aliasing or not aliasing '$'):

  • $(document).ready(handler)
  • $().ready(handler)
  • $(handler)
  • jQuery(function($) {});
  • jQuery(document).ready(function($) {});

Is that correct? Did I miss any?

like image 544
SooDesuNe Avatar asked Nov 09 '10 23:11

SooDesuNe


1 Answers

These are somewhat equivalent:

  • $(document).ready(handler) - tuns the handler when the DOM is loaded
  • $().ready(handler) - runs the handler when the DOM is loaded (deprecated, don't use)
  • $(handler) - runs the handler then the DOM is loaded - shortcut to $(document).ready(handler)
  • jQuery(function($) {}) same as #3 above, just using jQuery instead of the $ alias
  • jQuery(document).ready(function($) {}) - same as the first, again using jQuery instead of the $ alias

If $ is defined as something else, e.g. Prototype, then the first 3 won't work. The last 2 are similiar they're just accepting the first argument passed in (the jQuery object) and making it $ inside, making it possible to do this even when $ is something else:

jQuery(function($) {
  $("input").val("something");
});
like image 144
Nick Craver Avatar answered Oct 06 '22 00:10

Nick Craver