25 Mar, 2009

Published at 06:28PM

Tagged with javascript, jquery, and tips

This post has 3 comments

jQuery shorthand for $(document).ready()

Everyone who uses jQuery knows about this:

1
2
3
$(document).ready(function() {
  // your code
});

But did you know you can also do this:

1
2
3
$(function() {
  // your code
});

Not a huge difference, but it’s a nice shorthand alternative for those who enjoy having options :-)

Comments

Simon Monday, 30 Mar, 2009 Posted at 06:28AM

Even better, if you’re using jQuery.noConflict(), you can do this:

1
2
3
4
jQuery(function($) {
  // your code
  $('#mydiv').show();
});

Adam Saturday, 24 Oct, 2009 Posted at 10:05AM

When we use noConflict we tend to avoid using the $. We tend to run into problems with prototype.js and other open source JS librarys that also use the $ prefix.

If we are working with other libraries we would use the following:

1
2
3
4
jQuery.noConflict();
jQuery(function(){
     jQuery('#mydiv').show();
});

Ryan Sunday, 25 Oct, 2009 Posted at 12:19AM

@Adam -

Just to be clear, you can scope the $ function to use jQuery’s version only if/when inside of a jQuery function by passing it as a parameter. For example:

1
2
3
4
5
6
jQuery(function($) { // <= notice the '$' parameter
  
  // put your jQuery code here, because this
  // will use jQuery's $('...'), not Prototype's (or other)
  
});

Of course, you’re right in your example, but if you’d rather use the $ function (I prefer it) with .noConflict(), just pass it as a param to the function wrapping your jQuery code, and you’re good to go.

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch