HTML and CSS Reference
In-Depth Information
To implement the drop, you'll also need to provide the dragstart event handler. In the dragstart event
handler, you will store the id of the img element that is being dragged in the dataTransfer object. This will be
used by the drop event handler so it will know which element to remove.
eXerCISe 14-3. IMpLeMeNtING the DrOp
Add the following function to the existing script element, which will be used as the
dragstart event handler. This code gets the id of the source element (remember
the dragstart event is raised on the source element) which is the selected checker
image. This id is stored in the dataTransfer object. This function also specifies that
the allowed effects should be “move” since we'll be moving this image.
function dragStart(e) {
e.dataTransfer.effectAllowed = "move";
To provide the drop event handler add the code shown in Listing 14-5.
Listing 14-5. Implementing the drop event handler
function drop(e) {
// Prevent the event from being raised on the parent element
if (e.stopPropagation) {
// Stop the browsers default action
if (e.preventDefault) {
// Get the img element that is being dragged
var droppedID = e.dataTransfer.getData("text/plain");
var droppedPiece = document.getElementById(droppedID);
// Create a new img on the target location
var newPiece = document.createElement("img");
newPiece.src = droppedPiece.src; =, 1) +;
newPiece.draggable = true;
newPiece.addEventListener("dragstart", dragStart, false);;
// Remove the previous image
Search WWH ::

Custom Search