HTML and CSS Reference
In-Depth Information
The dragover event is fired continuously while dragging the element around on top of
the target, so we do not want to toggle on the red border in that handler (doing so
would create unnecessary work for the browser). However, we do need to prevent that
event's default behavior, depending on the type of element being dragged. This is why
we use preventDefault() and return false .
Lastly, we need to wire up a dataTransfer object with data that the browser needs for
handling the D&D actions. So, we'll modify our dragstart event handler like so:
foobar.addEventListener("dragstart", function(evt) {
this.style.border = "3px dotted #000"; // black dotted-line border
evt.dataTransfer.effectAllowed = "move";
evt.dataTransfer.setData("Text", this.id);
}, false);
The effectAllowed property controls what visual feedback—generally the mouse cur-
sor—the browser gives on the type of drag event that is occurring (move, copy, etc.).
The setData(...) method tells the D&D mechanism in the browser which data from
the element being dragged should be dropped into the target element, otherwise known
as the drop catcher . Here we specify that only the id property of the original element,
which is used later to actually move the element, is transferred.
Now we need to define a dragend event handler to clear up the visuals and a drop event
handler to actually do the moving of our element:
foobar.addEventListener( "dragend" , function(evt) {
this.style.border = ""; // remove the border
}, false);
catcher.addEventListener( "drop" , function(evt) {
if (evt.preventDefault) evt.preventDefault();
if (evt.stopPropagation) evt.stopPropagation();
this.style.border = ""; // remove the border from the catcher
var id = evt.dataTransfer. getData("Text") ; // get the id
var elem = document.getElementById(id);
elem.parentNode.removeChild(elem) ; // remove the element
this.appendChild(elem) ; // add the element back into our catcher
return false;
}, false);
In the drop event handler, we first get the data that was transferred in the drop, which
in this case was the id property of the original source element that we dragged. Next,
we remove that element from its current location, and finally add it back into the new
location inside our catcher container. The result is shown in Figure 10-2 .
 
Search WWH ::




Custom Search