Archive for September, 2006

Multiple $(document).ready()

Tuesday, September 5th, 2006

One more great thing about $(document).ready() that I didn't mention in my previous post is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your javascript file with them.

It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free.

You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:

HTML:
  1. <script src="/js/jquery.js" type="text/javascript"></script>
  2. <script src="/js/common.js" type="text/javascript"></script>
  3. <script src="/js/homepage.js" type="text/javascript"></script>

You could also do something like this inside a single .js file:

JavaScript:
  1. $(document).ready(function() {
  2.   // some code here
  3. });
  4.  
  5. $(document).ready(function() {
  6.   // other code here
  7. });

A final note: In a comment to my previous post, Jörn gave this excellent tip for shrinking your code:

Even for this little amount of code is a shortcut available:

$(function() {
// do something on document ready
});

A function passed as an argument to the jQuery constructor is bound to the document ready event.

Coming Up: In my next entry, I'll show how to do a simple effect with jQuery. You'll be amazed at how easy it is!

A Getting Started Guide

Sunday, September 3rd, 2006

Jörn Zaefferer has put together a nice "Getting Started Guide" that can help people, um, get started wtih jQuery. It'll help anyone who is new to jQuery, and even those who are fairly new to JavaScript and programming in general — just the kind of help I like. Here is what the guide includes:

  1. Setup
  2. Hello jQuery
  3. Find me: Using selectors and events
  4. Rate me: Using AJAX
  5. Animate me: Using FX
  6. Sort me: Using tablesorter plugin
  7. Plug me: Writing your own plugins
  8. Next steps

We'll be covering some of these topics here, too, but the more people who get the message out about how easy it is to use jQuery, the better.

Welcome to Learning jQuery!

Saturday, September 2nd, 2006

Welcome to the new Learning jQuery — a multi-author weblog with the aim of sharing information about this most amazing of JavaScript libraries. As we post entries, you might begin to notice that the three authors — Karl, Dan, and JonBob — approach jQuery, JavaScript, and life in general from three different perspectives. Our programming experience ranges from beginner to advanced, so we hope to appeal to all levels of other programmers out there as well. We'll do our best to make each entry clear, concise, and understandable, and we'll also try to place them in categories according to level of difficulty. If you have questions or critiques or suggestions for improvement, well, that's what the comments are for. Enjoy!

p.s. This entry probably should have been the first one on the blog, but in the rush and excitement to get this thing rolling, we jumped right in with some code.

Introducing $(document).ready()

Saturday, September 2nd, 2006

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

JavaScript:
  1. $(document).ready(function() {
  2.     // put all your jQuery goodness in here.
  3. });

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your javascript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href> tag.

On some pages that use traditional javascript, you'll see an "onload" attribute in the <body> tag. The problem with this is that it's limited to only one function. Oh yeah, and it adds "behavioral" markup to the content again. Jeremy Keith's excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate javascript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.

Sacrificial Lambda

Friday, September 1st, 2006

Dynamically binding event handlers to content that has been ajaxed in with $.load without repeating yourself can be tricky. Lambda functions help you to not repeat yourself as much. jQuery uses lamdba functions everywhere, so if you're familiar with jQuery, you should be familiar with the syntax of lambda functions.

In this example, the ajaxed-in content contains the elements that trigger a $.load over themselves.

JavaScript:
  1. prepare_links = function() {   
  2.   var month = $('.calendar-info .month').html();   
  3.   var year = $('.calendar-info .year').html();   
  4.   $('.previous-month').click(function() {
  5.      $('#calendar').load(this.href, prepare_links);
  6.      return false;
  7.   });
  8.   $('.next-month').click(function() {
  9.      $('#calendar').load(this.href, prepare_links);
  10.      return false;
  11.   });
  12. };
  13. $(document).ready(function() {
  14.    prepare_links();
  15. });

Make sure you're not calling the function in the callback by accidentally using prepare_links():

JavaScript:
  1. $('.next-month').click(function() {
  2.    $('#calendar').load(this.href, prepare_links()); /* Don't do this */
  3.    return false;
  4. });

This would set the callback to whatever the return value of the function is, not to the function itself.