HTML and CSS Reference
In-Depth Information
<div id="bucket1" class="bucket"></div>
<div id="bucket2" class="bucket"></div>
<div id="bucket3" class="bucket"></div>
<div id="chip" draggable="true" class="chip"></div>
The concept is that three buckets are defined by using div elements, and a chip is defined.
The user can drag the chip into any one of the three buckets. For the chip to be able to be
dragged, it must be draggable.
To begin the drag event, the dragstart must be handled:
var chip = document.getElementById("chip");
chip.addEventListener("dragstart", function ()
{ window.event.dataTransfer.setData("Text",; });
In this handler, the dataTransfer object setData method is used to store what exactly is
being transferred. In this case, the ID of the source object is specified.
Next, the desired target element's event listeners must be set up. The following code
shows this:
var b1 = document.getElementById("bucket1");
b1.addEventListener("dragenter", function () {
window.event.returnValue = false;
b1.addEventListener("dragleave", function () {
b1.addEventListener("dragover", function () {
window.event.returnValue = false;
b1.addEventListener("drop", function () {
window.event.returnValue = false;
var data = event.dataTransfer.getData("Text");
var d = document.getElementById(data);
In this code, the dragenter event listener is established so that the user gets a visual cue
with a transform that the element can be dropped onto. In the same token, the dragleave
event listener is set up to remove the effect. The dragover event is set to be ignored by
canceling it. This is only because div elements can't be dragged and dropped by default.
The last piece is the drop event handler. With this event handler, the drop is received. The
dataTransfer object's getData method is called to retrieve what's being dropped. The ID of the
source element gets a reference to the element and places it inside the target. The same code
can be repeated for the other two buckets, and then the chip can be dragged into each bucket.
Search WWH ::

Custom Search