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
$15.99 per month
Book Apr 2013 244 pages 1st Edition
$28.99 $19.99
$15.99 Monthly
$28.99 $19.99
$15.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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


What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.