dataTransfer object belongs to the event object during the drag&drop operations. It provides a way of storing temporary data for use during drag&drop. Let me show you what you can do with the dataTransfer object.

  • :bell:Storing temporary data:

Data about the dragged DOM element can be stored in dataTransfer using setData() method and be retrieved during the drop stage.

dragElement.ondragstart = function(e) {
    e.dataTransfer.setData("text/plain", e.target.id);
};
dropElement.ondrop = function(e) {
    e.target.appendChild(e.dataTrnasfer.getData("text"));
};
  • :bell:Setting draged element icon:

When you drag an element on the web page, you can set an custom icon near the mouse cursor to indicate that the element is being dragged.

dragElement.ondragstart = function(e) {
    e.dataTransfer.setDragImage(img, 10, 10);
};
  • :bell:Creating visual drag&drop effect:

There are three drag&drop effects available, copy, move and link. They are mostly used to produce visual feedback to users when the dragged element is over the dropped area. The default drop effect for chrome is “copy”.

dragElement.ondragover = function(e) {
    e.dataTransfer.dropEffect = "move";
};

Besides the above three key points for dataTransfer object, let’s recap other important points to note for performing a drag&drop operation.

  • :bell:Make the element draggable:

Not all elements in HTML are draggable by default. For example, images are draggable by default. For most of the elements, you have to set the draggable attribute to true in order to perform drag&drop operations.

<div id="source" draggable="true"></div>
  • :bell:Drag&drop events:

There are eight drag&drop events of which three are for drag events and five are for drop events:

dragElement.ondragstart = function(e) {
    //performing dragstart actions
};
dragElement.ondrag = function(e) {
    //performing drag actions
};
dragElement.ondragend = function(e) {
    //performing dragend actions
};
dropElement.ondragenter = function(e) {
    //performing actions when entering drop area
};
dropElement.ondragover = function(e) {
    //performing actions when being over drop area
};
dropElement.ondragleave = function(e) {
    //performing actions when leaving drop area
};
dropElement.ondragexit = function(e) {
    //performing actions when exiting drop area
};
dropElement.ondrop = function(e) {
    //performing actions when being dropped on drop area
};
  • :bell:Preventing default behavior:

When performing drag&drop actions, the default behavior for some of the events must be prohibited, namely the default behavior for dragover event. Of course you can prevent the default behavior for event of every drag&drop stage to meet the browser compatibility requirement.

dropElement.ondragover = function(e) {
    e.preventDefault();
};

You can find more information on the mozilla developer network website:link:mozillar developer network