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
1.
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";
e.dataTransfer.setData("text/plain", e.target.id);
}
2.
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) {
e.stopPropagation();
}
// Stop the browsers default action
if (e.preventDefault) {
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;
newPiece.id = droppedPiece.id.substr(0, 1) + e.target.id;
newPiece.draggable = true;
newPiece.classList.add("piece");
newPiece.addEventListener("dragstart", dragStart, false);
e.target.appendChild(newPiece);
// Remove the previous image
droppedPiece.parentNode.removeChild(droppedPiece);
}
 
Search WWH ::




Custom Search