jQuery – Explaining Last Week’s Code

ka_vol1_070 Last week I left you with a chunk of code that showed you that you had successfully installed jQuery into your web application.

The code we need to discuss looks like this:

$(document).ready(function() {
    alert("jquery is working");

The first piece of code we need to examine is the document selector:


The $(…) syntax is called a selector. In this case we are telling the selector to find the document. We can tell it to find other things as well. Tags, IDs, all items with a specific class. But today we are selecting the document object.

Since selecting the document is a pretty common activity, you may also see it abbreviated:


The second hunk of code we need to examine should be pretty familiar if you have done any recent work in javascript:

function() {
    alert("jquery is working");

This is a standard pseudo function. Pseudo functions are handy when we need to pass a pointer to a function into another javascript function but that is the only place we are going to need it. Most of the time a startup script fits that description.

Last is the .ready event handler.

Event handler?

Yep. One of the features jQuery gives us is the ability to add on events to some of the standard events we’ve been using.

In this case, we have a ready event that takes a pointer to a function as a parameter.

This is similar, but significantly different from, the onload event you may be used to. If you need to use the onLoad event handler, you use the jQuery load event handler instead.

What’s the difference?

The load event fires once the document has loaded. But have you ever had a timing error where the document was loaded but the DOM wasn’t ready to process? That’s what the .ready handler is for. It only fires once everything is ready to be processed.

It’s a minor difference to be sure, but it solves a ton of problems.

The .ready event is also so familiar that we can short-cut it with the selector.

$(function() {
    alert("jquery is working");

I’m sure there are all kinds of religious discussions on the web about what the most readable syntax is. Personally, I would argue that they are all readable once you know how to read them.


Other post in jQuery

Related Post

One Response to “jQuery – Explaining Last Week’s Code”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail