Deconstructing JQuery syntax

From Knowledge Kitchen
Jump to navigation Jump to search

JQuery's syntax can be confusing. Don't worry, it's going to be ok.

Let's first deconstruct some of the more common JQuery commands that you'll come across, so you can start to recognize the common elements in all JQuery scripts.

If you understand Javascript properly, JQuery will not be difficult to use.

The JQuery $ function

At its heart, JQuery is just a single function:

  • the name of the JQuery function is $
  • you call that function the same way you would call any function: $();
  • you can pass arguments to that function the same way you would pass arguments to any function $("foo");
  • the return value of that function depends on what arguments you give it
    • This is where JQuery gets interesting.
var allImagesOnThePage = $("img");

Wating for the page to load

First, and most importantly among the useful tricks of JQuery is $(function() { ... });, which can also be written as $(document).ready(function() { ... }). This is the command we use to wait until the page is loaded before doing any manipulation of elements on the page.

A note about object-oriented programming

In case you forgot, objects are specific instances of classes (e.g., a specific Ford Mustang might be an instance - i.e., an object - of a Car class). Objects have both properties and methods, which are basically variables and functions that "belong to" the object.

A note about the web browser's DOM

By default the web browser automatically creates an object that it calls 'document' that has a variety of properties and methods related to the contents of the current web page. This document object is the highest level object in the Document Object Model (DOM), which is the internal representation the browser has of the contents of any page.

What the JQuery ready() function does

The ready() method is an extra method that JQuery adds on to the browser's existing 'document' object. It offers a relatively simple way to run some code only once the page has finished loading. This method takes one parameter, which is the function to run when the page is ready.

To extend the 'document' object so that it has this extra ready() method (as well as many other extra JQuery properties and methods), we wrap it in the $() function. So we write '$(document)' whereas in regular Javascript, we would use just 'document'. This '$()' indicates that we want to use the extended JQuery version of this object, with the extra methods and properties. As you might have guessed, based on your knowledge of function return values, this function returns the modified document object. You can use this same technique for any element in the DOM that you want to extend with JQuery's extra properties and functions.

How to call JQuery's ready() function

So in the end, $(document).ready(some_function) is the way we call this extended document object's ready() function. We pass it, as a parameter, the function we want called when the page is ready.

some_function can either be the name of the function to call, or the definition of the function itself. So you could have code that looks like this:

function doSomething() {
  //some code that you want to run when the page loads
$(document).ready(doSomething);  //call the doSomething() function when the page is ready

An alternative way to call JQuery's ready() function

As an alternative to the example above, we could use an alternative syntax, which takes advantage of Javascript's ability to write anonymous functions, meaning functions with no name that are only used once:

$(document).ready(function() {
  //some code that you want to run when the page loads

These two code snippets are functionally identical as far as the browser is concerned. The latter syntax, using an anonymous function as a parameter, is more common in this context among experienced developers, since it is more compact.

Creating an event handler

The next most common thing you will want to do in JQuery code is create an event handler. This means creating a block of Javascript code that responds to a browser event, be it a click, mouseover, mouseout, keypress, keyup, or any other type of event. JQuery makes this process standardized, and quite simple.

What a JQuery event handler looks like

A typical JQuery click event handler will look something like this:

$("a.class1").click(function(event) {
  //some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector

JQuery uses CSS-style selectors

Let's dissect the code in the example above. Let's first look at the first part:


Once again, we see the ubiquitous '$()' JQuery function. This time, it is wrapped around a CSS-style selector:


As you know, if this were CSS code, that selector would match any <a> tag with class='class1'. And it works exactly the same way here, because the developers of JQuery decided that this type of selector is easy to use.

What the JQuery $() function returns

Putting a CSS-style selector as a String literal like this between the parentheses (as a parameter) of the $() function tells JQuery to return an array (i.e., a list) of all DOM elements that match this selector.

For all the elements that match this selector, we attach a 'click' event handler. An 'event handler' is just code that does something in response to an event: in this case the event would be a user clicking on any of the matching <a> elements. To attach the event handler to these elements, we call the click() method of the matching DOM elements. This click() method is is one of those method that JQuery adds as an extension to the default DOM element methods.

Any time you use the $() function to get a single element, or a list of elements, you can be sure that the objects that are returned by that function have the additional extended methods and properties that JQuery provides. So now you know that click() is an extended method of any DOM element returned by the $() function, and it takes one parameter: the function to run when a user clicks one of the matching elements.

How to call a JQuery event handler function

Like the $(document).ready() method, we can think of this method as looking something like this:


The some_css_selector indicated in this code would be a CSS-style selector, such as 'a.class1. And just as with the $(document).ready() function, some_function can be either the name of an existing function, or an anonymous function definition, as illustrated in the following two equivalent ways of doing this task. First the long-winded way of doing it:

function doSomething(event) {
  //some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector

The event object

You may notice that our function's signature, 'function doSomething(event)', takes a parameter that we call 'event'. This paramater automatically gets passed by JQuery to any function that called as an event handler. And so the 'event' variable in that function holds the a special JQuery Event object that has properties and methods related to the browser event that triggered this event handler to be called. In this case, the 'event' object has properties and methods related to the 'click' event that caused the function to get called. For example, the event.type property would hold the type of event, be it 'click', 'mouseover', or something else. And event.preventDefault() is a method of the JQuery Event object that prevents links or forms from actually taking the user to another page.

The directly equivalent, but more compact, way of writing this same event handler using an anonymous function definition would be:

$("a.class1").click(function(event) {
  //some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector

Which method you choose is up to you, but you will probably see both being used by other developers. The two are equivalent as far as the browser is concerned.

The this

Within any function that gets called as a the result of an event handler, we have a special variable called 'this'. This variable automatically holds the DOM element that triggered the event.

For example:

$("a.class1").click(function(event) {
  //some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector

The 'this', in this example, holds the regular Javascript DOM element that triggered the 'click' event, which was handled by the anonymous function that is passed as a parameter to the click() method.

If we want to use JQuery to modify this DOM element, we have to first extend it by wrapping it in $(). So we write $(this) in order to be able to use the special JQuery methods and properties, like addClass() that JQuery adds to regular DOM elements. The addClass() method is a simple method that takes a single parameter, the name of a CSS class to add to the element. In this case, we are using it to add the class, 'selected', to the element that was clicked.

Putting it all together

So taking a real-world example'. the way you would use JQuery to handle an event is by combining the above methods. First you would wait for the page to finish loading, using the $(document).ready() method. And as the sole parameter to this ready() method, you would pass a function that defined an event handler.

For example:

$(document).ready(function() {
  //some code that you want to run when the page loads  
  $("a.class1").click(function(event) {
    //some code that you want to run when the user clicks any element that matches the "a.class1" CSS-style selector

See how we have nested the 'click' event handler within the anonymous function that gets called when the page is 'ready'. This makes sure that the event handler is only set after the page has loaded, thereby assuring that the DOM elements of the page that we want to modify are already loaded and available to be modified.

What links here