Game Development Reference
In-Depth Information
In this example, we append a new list element to the unordered list every time a list
element is dropped anywhere on the page, since every element on the page is a
child of the body node. Also, whenever a draggable element hovers over the body
element, we add a CSS class called dropme , which is meant to give the user a visu-
al feedback letting them know that the drag event is taking place. When the drag-
gable is dropped, we remove that class from the body element indicating the end of
the drag action.
One thing we can do with the drag and drop API is transfer data between objects.
This data can be a string, or any data type that can be converted into a string. We
do this by setting the desired data to the dataTransfer object available to us dur-
ing the drag action. The data must be set when the drag start function is fired by the
system. The key associated with the dataTransfer data can be any string of our
choosing as shown in the following code:
function doOnDragStart(event) {
// First we set the data when the drag
event first starts
event.dataTransfer.setData("who-built-me",
event.target.getAttribute("data-name"));
}
function doOnDrop(event) {
event.preventDefault();
document.body.classList.remove("dropme");
var num =
document.querySelectorAll("li").length + 1;
// Then we retrieve that data when the drop
event is fired by the browser
var builtBy =
event.dataTransfer.getData("who-built-me");
var newItem = document.createElement("li");
newItem.ondragstart = doOnDragStart;
newItem.setAttribute("draggable", true);
newItem.setAttribute("data-name", "Block "
Search WWH ::




Custom Search