Search icon CANCEL
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Learning Hub
Free Learning
Arrow right icon
jQuery Game Development Essentials
jQuery Game Development Essentials

jQuery Game Development Essentials: Learn how to make fun and addictive multi-platform games using jQuery with this book and ebook.

By Selim Arsever
€28.99 €19.99
Book Apr 2013 244 pages 1st Edition
€28.99 €19.99
€14.99 Monthly
€28.99 €19.99
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

jQuery Game Development Essentials

Chapter 1. jQuery for Games

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 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

The way of jQuery

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:


With chaining, this would be written as:


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:

   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 (

We will now focus on a few functions that are of interest for developing games.

Moving things around

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.

Chaining animations

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(), and fadeTo()

  • hide() and show()

  • slideUp() and slideDown()

Managing the queue

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.

.animate({top: 200})
.animate({left: 200})


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:


Other usages of queues

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.

Handling of events

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").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.

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.

Removing event handlers

If you need to remove an event handler you can simply use the .unbind() and .undelegate() functions.

jQuery 1.7

In jQuery 1.7, .delegate() and .bind() have been replaced by .on() (and .off() to remove the handlers). Think of it as a .delegate() function with the capacity to behave like .bind(). If you understand how .delegate() works, you will have no problem to use .on().

Associating data with DOM elements

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 (, 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.

Manipulating the DOM

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.

Stay curious my friend!

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:


In this chapter, we've seen some of the most useful jQuery functions for game development and how to use them. By now you should be familiar with the jQuery philosophy and syntax. In the next chapter, we will put what we've learned into practice and create our first game.

Left arrow icon Right arrow icon

Key benefits

  • Discover how you can create a fantastic RPG, arcade game, or platformer using jQuery!
  • Learn how you can integrate your game with various social networks, creating multiplayer experiences and also ensuring compatibility with mobile devices.
  • Create your very own framework, harnessing the very best design patterns and proven techniques along the way.
  • The updated code files can be found here


jQuery is a leading multi-browser JavaScript library that developers across the world utilize on a daily basis to help simplify client-side scripting. Using the friendly and powerful jQuery to create games based on DOM manipulations and CSS transforms allows you to target a vast array of browsers and devices without having to worry about individual peculiarities."jQuery Game Development Essentials" will teach you how to use the environment, language, and framework that you're familiar with in an entirely new way so that you can create beautiful and addictive games. With concrete examples and detailed technical explanations you will learn how to apply game development techniques in a highly practical context.This essential reference explains classic game development techniques like sprite animations, tile-maps, collision detection, and parallax scrolling in a context specific to jQuery. In addition, there is coverage of advanced topics specific to creating games with the popular JavaScript library, such as integration with social networks alongside multiplayer and mobile support. jQuery Game Development Essentials will take you on a journey that will utilize your existing skills as a web developer so that you can create fantastic, addictive games that run right in the browser.

What you will learn

Create sprite-based, multi-platform games using the latest web standards and jQuery Use powerful techniques directly from the games industry to make your own games harness stunning visual effects without compromising on performance Learn how you can develop real-time multiplayer games and integrate them with social networks Overcome the limitations of mobile browsers allowing you to take full advantage of their various features with minimum hassle Develop a platformer, an arcade game, or even your very own RPG with jQuery at the core Discover how you can easily implement features like parallax scrolling Utilize your existing skills in jQuery in a fun and exciting new context

Product Details

Country selected

Publication date : Apr 25, 2013
Length 244 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849695060
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details

Publication date : Apr 25, 2013
Length 244 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849695060
Category :

Table of Contents

17 Chapters
jQuery Game Development Essentials Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. jQuery for Games Chevron down icon Chevron up icon
2. Creating Our First Game Chevron down icon Chevron up icon
3. Better, Faster, but not Harder Chevron down icon Chevron up icon
4. Looking Sideways Chevron down icon Chevron up icon
5. Putting Things into Perspective Chevron down icon Chevron up icon
6. Adding Levels to Your Games Chevron down icon Chevron up icon
7. Making a Multiplayer Game Chevron down icon Chevron up icon
8. Let's Get Social Chevron down icon Chevron up icon
9. Making Your Game Mobile Chevron down icon Chevron up icon
10. Making Some Noise Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial


How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to
  • To contact us directly if a problem is not resolved, use
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.