Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

528 CHAPTER 13 Drag and drop


Your code should look like the following.
function drop(e) {
var $square= $(e.target);
if ($square.hasClass('square')) {
var destinationLocation = $square.data('square');
if (emptySquare != destinationLocation) return;
var sourceLocation = Number(e.dataTransfer.getData('text'));
moveTile(sourceLocation);
}
}


  1. Under the drop function, add a moveTile function that takes the sourceLocation
    parameter. In this function, add a statement to create a distance variable that is set to
    the sourceLocation parameter minus the emptySquare value.

  2. Add a statement to make the distance a positive value if it’s negative. Compare the
    distance to 1 or 4, in which the value of 1 indicates a drop from a horizontally adja-
    cent square, and a value of 4 indicates a drop from a vertically adjacent square. If
    the distance is equal to 1 or 4, call the swapTileAndEmptySquare function with the
    sourceLocation parameter.
    Your code should look like the following.
    function moveTile(sourceLocation) {
    var distance = sourceLocation - emptySquare;
    if (distance < 0) distance = -(distance);
    if (distance == 1 || distance == 4) {
    swapTileAndEmptySquare(sourceLocation);
    }
    }

  3. Under the moveTile function, add a swapTileAndEmptySquare function that takes the
    sourceLocation parameter. In this function, use jQuery to retrieve the tile from the tile
    at the sourceLocation parameter and assign the value to a $draggedItem variable. Use
    jQuery to detach the dragged item from the document object model (DOM). Create
    a $target variable and assign the square at the emptySquare location. Use jQuery to
    append the dragged item to the target.

  4. Assign sourceLocation to emptySquare.
    The following is the complete default.js file.
    ///


var squareCount = 16
var emptySquare;

$(document).ready(function () {
jQuery.event.props.push('dataTransfer');
createBoard();
addTiles();
$('#gameBoard').on('dragstart', dragStarted);
$('#gameBoard').on('dragend', dragEnded);
Free download pdf