Over the course of the last few years, jQuery has almost become the default framework for any JavaScript development. More than 55 percent of the top 10,000 most visited websites as well as an estimated total of 24 million websites on the Internet are using it (more at http://trends.builtwith.com/javascript/JQuery). And this trend doesn't show any sign of stopping.
This book expects you to have some prior experience of jQuery. If you feel that you don't meet this requirement, then you could first learn more about it in Learning jQuery, Jonathan Chaffer, Karl Swedberg, Packt Publishing.
This chapter will quickly go through the peculiarities of jQuery and will then dive deeper into its most game-oriented functions. Even if you probably have already used most of them, you may not be familiar with the full extent of their capabilities. The following is a detailed list of the topics addressed in this chapter:
The peculiarities of jQuery
The function that will help you for moving elements around
Event handling
DOM manipulation
jQuery's philosophy differs from most other JavaScript frameworks that predated it. Understanding the design patterns it uses is key to writing readable and efficient code. We'll cover these patterns in the next sections.
Most jQuery statements are of the following form: a selection followed by one or more actions. The way those actions are combined is called chaining and is one of the most elegant aspects of jQuery. A beginner using jQuery who wants to set the width of an element to 300 pixels and its height to 100 pixels would typically write something like:
$("#myElementId").width(300); $("#myElementId").height(100);
With chaining, this would be written as:
$("#myElementId").width(300).height(100);
This has many advantages: the element is selected only once, and the resulting code is more compact and conveys the semantic meaning that what you want to achieve is really only one thing, which is to change the element size.
Functions that allow chaining don't only make it possible to group many calls on the same object, but also there are many ways to actually change on what object (or objects) the next function on the chain will operate. In these situations, it is typical to use indentation to convey the idea that you're not working on the same elements as the previous indentation level.
For example, the following chain first selects an element, then sets its background's color as red
. It then changes the elements in the chain to the children of the previous element and changes their background-color
attribute to yellow
.
$("#myElementId").css("background-color", "red") .children().css("background-color", "yellow");
It's important that you always ask yourself how the current interactions with the previous and next element in the chain can be avoided for undesired behavior.
jQuery has its own way to use polymorphism, and a given function can be called in a lot of different ways depending on how much information you want to give to it. Let's have a look at the .css()
function. If called with a String
data type as the only argument, this function will behave as a getter by returning the value of the CSS property you asked for.
For example, the following line retrieves the left-hand side position of a given element (assuming it's positioned absolutely):
var elementLeft = $("#myElementId").css("left");
However, if you pass a second argument, it will start to behave like a setter and set the value of the CSS property. The interesting thing is that the second argument can also be a function. In this situation, the function is expected to return the value that will be set to the CSS property.
The following code does just that and uses a function that will increase the left-hand side position of the element by one:
$("#myElementId").css("left", function(index, value){ return parseInt(value)+1; });
However; wait, there's more! If you pass just one element to the same function, but that element is an object literal, then it will be considered as holding a map of properties/values. This will allow you to change many CSS properties in one single call, like setting the left and top position to 100 pixels in the following example:
$("#myElementId").css({ left: 100, top: 100 });
You can also use strings as the key and value of your object literal as it's done in JSON.
A very complete resource for finding about all the ways to call a function is the jQuery API website (http://api.jquery.com).
We will now focus on a few functions that are of interest for developing games.
Chaining has a slightly different signification for animation. Though you may never actually need to use jQuery animation functions in most of your games, it may still be interesting to see the peculiarities of their functioning as it may be the cause of many strange behaviors.
The
.animate()
function from jQuery allows you to make a property vary through time from the current value to a new one. A typical effect, for example, would be to move it left from 10 pixels, or change its height. From what you've seen earlier and experienced for other type of functions, you may expect the following code to make a div (DOM division element) move diagonally to the position left = 200px
and top = 200px
.
$("#myElementId").animate({top: 200}).animate({left: 200});
However, it doesn't! What you will see instead is the div first moves to reach top = 200px
and only then moves to left = 200px
. This is called queuing; each call to animate
will be queued to the previous ones and will only execute once they're all finished. If you want to have two movements executed at the same time, thereby generating a diagonal movement, you'll have to use only one call to .animate()
.
$("#myElementId").animate({top: 200,left: 200});
Another possibility is to explicitly tell the .animate()
function not to queue the animations:
$("#myElementId").animate({top: 200}).animate({left: 200},{queue: false});
Keep in mind that this also applies to other functions that are in fact wrappers around the .animate()
function, such as the following:
fadeIn()
,fadeOut()
, andfadeTo()
hide()
andshow()
slideUp()
andslideDown()

Here is a list of functions that you can use to manipulate this queue of animations.
The
.stop()
function stops the current animation of the queue. If you provide some more arguments to the call, you can also clear the queue and define if the elements should stop being animated and stay where they are, or jump to their destination.
The .clearQueue()
function removes all animations from the queue; not only the current one, but also all the next ones.
The .dequeue()
function starts the next animation in the queue. This means that if an animation is being executed when this function is called, then the new one will start as the current one finishes executing. For example, if we take the example at the beginning of this section and add a dequeue()
function at the end, the elements will actually start moving diagonally.
$("#myElementId") .animate({top: 200}) .animate({left: 200}) .dequeue();
The .delay()
function allows you to insert a pause between two animations in the queue. For example, if you want to make an element visible with .fadeIn()
, then wait for 2 seconds and make it disappear again with .fadeOut()
. This would be written like this:
$("#myElementId").fadeIn().delay(2000).fadeOut();
Queues are not used only for animations. When you don't specify otherwise, the queue manipulated by those functions is the fx
queue. This is the default queue used by animations. However, if you want to, you could create another queue and add any number of custom functions and delays to script some time-dependent behavior in your game.
If you have used jQuery before, you probably used .click()
at some point. It is used to define an event handler that will respond to a mouse click in jQuery. There are many more of those, going from keyboard input, form submission, and window resizing, but we will not go through all these. Instead we will focus on the more "low-level" functions to handle events in jQuery and explain exactly the subtle differences between them.
You would typically use some of those functions to implement the control of your games either with mouse or keyboard inputs.
The .bind()
function is the basic way to handle events. .click()
is, for example, just a wrapper around it. The two lines of the following example have exactly the same effect:
$("#myElementId").click(function(){alert("Clicked!")}); $("#myElementId").bind('click', function(){alert("Clicked!")});
However, there is a limitation with the usage of bind
. Like all other jQuery functions, it only applies to the selected elements. Now, imagine a situation where you want to execute some task each time a user clicks a link with a given class. You would write something like this:
$(".myClass").click(function(){/** do something **/});
This will work as intended, but only for the link present in the webpage at the moment of its execution. What if you change the content of the page with an Ajax call, and the new content also contains links with this class? You will have to call this line of code again to enhance the new links!
This is far from ideal, because you have to manually track all event handlers you defined that may require to be called again later and all the places where you change the content of the page. This process is very likely to go wrong and you'll end up with some inconsistencies.
The solution to this problem is .delegate()
, which is explained in detail in the following section.
With .delegate()
, you give the responsibility of handling events to a parent node. This way all elements added later on as a child to this node (directly under it or not) will still see the corresponding handler execute.
The following code fixes the preceding example to make it work with a link added later on. It's implied that all those links are children of a div with the ID
attribute as page
.
$("#page").delegate( ".myClass", "click", function(){/** do something **/});
This is a very elegant way to solve the problem and it will come in very handy while creating games, for example, where you click on sprites.
Let's say you create a div element for each enemy in your game. You will probably want to associate them to some numerical value, like their life. You may even want to associate an object if you're writing object-oriented code.
jQuery provides a simple method to do this, that is, .data()
. This method takes a key and a value. If you later call it with only the key, it will return the value. For example, the following code associates the numerical value 3
with the key "numberOfLife"
for the element with ID enemy3
.
$("#enemy3").data("numberOfLife", 3);
You may be thinking, "Why shouldn't I simply store my values directly on the DOM element?". There is a very good answer for that. By using .data()
, you completely decouple your value and the DOM, which will make it way easier to avoid a situation where the garbage collector doesn't free the memory associated with the DOM of a removed element because you're still holding some cyclic reference to it somewhere.
If you defined some values using the HTML5 data attribute (http://ejohn.org/blog/html-5-data-attributes/), the .data()
function retrieves them too.
However, you have to keep in mind that making calls to this function has some performance cost, and if you have many values to store for an element, you may want to store all of them in an object literal associated with a single key instead of many values, each associated with their own key.
While creating a game with jQuery, you will spend quite some time adding and removing nodes to the DOM. For example, you could create new enemies or remove dead ones. In the next section we'll cover the functions you will be using and we will also see how they work.
This function allows you to add a child to the currently selected element (or elements). It takes as argument some already existing DOM element, a string containing HTML code that describes an element (or a whole hierarchy of elements), or a jQuery element selecting some nodes. For example, if you wanted to add a child to a node with the ID "content"
, you would write:
$("#content").append("<div>This is a new div!</div>");
Keep in mind that if you give a string to this function, the content will have to be parsed and that this could have some performance issues if you do it too often or for very large strings.
This function works exactly like .append()
, but adds the new content before the first child of the selected element instead of after its last one.
This function allows you to completely replace the content of the selected node(s) with the string passed as an argument. If called without an argument, it will return the current HTML content of the first of the selected elements.
If you call it with an empty string, you will erase all the content of the nodes. This could also be achieved by calling .empty()
.

This function will simply delete all the selected elements and unregister all the associated event handlers and data.
In some situations, you may only want to remove some content for a short period of time and add it again later. This is typically a case where .remove()
does too much of a good job. What you really want is to keep all those other things you associated with your nodes so that when they get added later on, they will work exactly like before. .detach()
has been created exactly for this situation. It will behave like .remove()
, but will allow you to reinsert your elements easily.
So that's it. I would really encourage you to read the API for each of these functions because there are still some sets of arguments that have not been shown here. If anything is still unclear about any of those functions, don't hesitate to look around the Web for more examples on how to use them. As jQuery is such a popular library, and the Web's culture is one of openness, you will easily find lots of help online.
Here are some places where you can start looking for more information about jQuery:
jQuery's API: http://api.jquery.com/
Learning jQuery: http://www.learningjquery.com/