Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 13 525


These functions are created next. Your code should look like the following.
/// <reference path="jquery-1.8.3.js" />

var squareCount = 16
var emptySquare;

$(document).ready(function () {
jQuery.event.props.push('dataTransfer');
createBoard();
addTiles();
});


  1. Under the document ready function, add a createBoard function. In this function, add
    a for loop that loops while the loop variable is less than the squareCount variable. In
    the for loop, use jQuery to create a
    element whose id is square plus the value of
    the loop variable. Add a data-square attribute and assign the loop variable’s value. Add
    the class attribute and assign the square class. Append the newly created square to the
    game board.
    Your code should look like the following.
    function createBoard() {
    for (var i = 0; i < squareCount; i++) {
    var $square = $('<div id="square' + i + '" data-square="'

    • i +'" class="square">
    ');
    $square.appendTo($('#gameBoard'));
    }
    }



  2. Under the createBoard function, add an addTiles function. In this function, add a state-
    ment to assign the value of the squareCount variable minus one to the emptySquare
    variable. Add a for loop that loops while the loop variable is less than the emptySquare
    value. In the for loop, use jQuery to get a reference to the square that corresponds to
    the loop variable. Use jQuery to create a
    element whose id is tile plus the value
    of the loop variable. Add a draggable attribute and set its value to true. Add the class
    attribute and assign the tile class. In the content of this
    element, put the value of
    the loop variable plus one. Append the newly created tile to the corresponding square.
    Your code should look like the following.
    function addTiles() {
    emptySquare = squareCount - 1;
    for (var i = 0; i < emptySquare; i++) {
    var $square = $('#square' + i);
    var $tile = $('<div draggable="true" id="tile' + i

    • '" class="tile">' + (i + 1) + '
    ');
    $tile.appendTo($square);
    }
    }



Free download pdf