Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 13 527


$('#gameBoard').on('dragover', preventDefault);
$('#gameBoard').on('drop', drop);
});


  1. At the bottom of the default.js file, add the dragStarted function that takes an e event
    parameter. In this function, create a $tile variable that is a jQuery wrapper for e.target.
    Use $tile to add the dragged CSS class to the tile. Declare a sourceLocation variable and
    assign to it the value of the data-square attribute from the tile’s parent (the square).
    The sourceLocation is the square number the tile is in.

  2. Assign the string value of sourceLocation to the DataTransfer object and set the
    effectAllowed property to move. Your code should look like the following.
    function dragStarted(e) {
    var $tile = $(e.target)
    $tile.addClass('dragged');
    var sourceLocation = $tile.parent().data('square');
    e.dataTransfer.setData('text', sourceLocation.toString());
    e.dataTransfer.effectAllowed = 'move';
    }

  3. After the dragStarted function, add a dragEnded function. In this function, use jQuery
    to remove the dragged CSS class from the tile.
    Your code should look like the following.
    function dragEnded(e) {
    $(e.target).removeClass('dragged');
    }

  4. Under the dragEnded function, add a preventDefault function that takes an e event
    parameter. In this function, add a statement to call the preventDefault method on e.
    Your code should look like the following.
    function preventDefault(e) {
    e.preventDefault();
    }

  5. Under the preventDefault function, add a drop function that takes an e event parame-
    ter. In this function, add a statement to create a jQuery wrapper for e.target and assign
    it to a $square variable. Add an if statement to verify that the target of the drop is a
    square by checking to see whether $square has the CSS class called square. If so, use
    jQuery to add code that reads the data-square attribute $square and place the value in
    a destinationLocation variable. Compare the value of emptySquare with the value of the
    destination location and, if they are not equal, exit the drop function by using a return
    statement.

  6. Add code to get the data from the DataTransfer object. Assign it to a sourceLocation
    variable and then call the moveTile function that you create next, passing the
    sourceLocation variable.

Free download pdf