HTML and CSS Reference
In-Depth Information
var timer = setInterval(nextElement,500);
$("#container").on('mousedown','div',function(e) {
countup++;
$(this).fadeOut();
});
The first thing this code does is get the dimensions of the window using jQuery; then it defines a couple of
variables to store the number of blocks left to display and the number the user has clicked.
It then defines a nextElement function that is called each time a block is to be added to the page. This
function first checks if the game is over by looking at the countdown variable and calls the gameOver meth-
od if it is. If the game is not over, a random x and y position is generated and a new 50-by-50-pixel red square
block is created, styled, and positioned on the screen.
The gameOver function first clears the interval timer, so that no more elements are added onto the page,
and then pops up an alert message either telling the player that they won or lost.
Next is a call to setInverval to ensure a new block is created every 500 milliseconds.
Finally, with one call to $(selector).on , the game captures all the mousedown events on all the <di-
v> s inside the #container element, even for elements that have not yet been created. When the player clicks
a <div> , the countup variable is increased, and the element is faded out. In this case the mousedown event
is used instead of a click event because the click event requires the mouse to be released over the same
element as it is clicked on, which slows down the game.
NOTE Users can cheat in the Block Clicker game by clicking the fading element quickly in succession. Can
you think of a way to prevent this?
Making Ajax Calls
So far, only one aspect of jQuery has been discussed in detail, DOM manipulation, but the library has some
more useful tricks. jQuery also provides a simple and consistent interface for making AJAX call back to a web
server. Using AJAX allows your game to push and pull data to and from a web server without requiring a full
page reload. One thing to remember when making Ajax calls is that they are, by definition, asynchronous. This
means that you can't be sure when they are going to be finished.
Calling Remote Servers
jQuery provides one method to rule them all when it comes to making Ajax calls, called $.Ajax . If you look
at the documentation for $.Ajax at http://api.jquery.com/jQuery.ajax/ , you can notice that the method takes
more than 30 different options to configure various parts of the request being made.
This level of configurability can be overwhelming when you just want to send or grab some data. Luckily
jQuery provides a few shorthand methods. For example, say you want to load a JSON file of level data; you
could simply write:
$.getJSON("level1.js",function(levelData) {
// Do something with your levelData
});
 
Search WWH ::




Custom Search