HTML and CSS Reference
In-Depth Information
i = 0;
var pieces = document.querySelectorAll('img');
while (i < pieces.length){
var p = pieces[i++];
p.addEventListener('dragstart', dragStart, false);
p.addEventListener('dragend', dragEnd, false);
}
5.
now you'll need to make a couple of changes to the drop event handler. You add
the “drop” class to the target element in the
dragenter
event and then remove it in
the
dragleave
event. However, if they drop the image, the
dragleave
event is not
raised. You'll also need to remove the “drop” class in the
drop
event as well. Also,
when creating a new
img
element you'll need to wire up the
dragend
event handler.
6.
Add the code shown in bold.
// 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);
newPiece.addEventListener("dragend", dragEnd, false);
e.target.appendChild(newPiece);
// Remove the previous image
droppedPiece.parentNode.removeChild(droppedPiece);
// Remove the drop effect from the target element
e.target.classList.remove('drop');
7.
Finally, you'll need to define the CSS rules for the “drop” and “selected” values. I've
chosen to set the
opacity
attribute but you could just as easily add a border, change
the background color, or any number of effects to achieve the desired purpose.
8.
Add the following rules to the existing
style
element.
.bblack.drop
{
opacity: 0.5;
}
.piece.selected
{
opacity: 0.5;
}