---
title: "Drag & Drop"
framework: javascript
version: "36.1.0"
---

# Drag & Drop

Drag & Drop is concerned with moving data around an application, or between applications, using the operating system drag and drop support. When using drag and drop, data is moved or copied around using MIME types in a way similar to using the clipboard.

Native drag and drop is typically used for moving data between applications, e.g. moving a URL from an email into a web browser to open the URL, or moving a file from a file explorer application to a text editor application. Native drag and drop is not typically used for operating on data inside an application. Native drag and drop is similar to clipboard functionality, e.g. data must be represented as MIME types and objects cannot be passed by reference (the data must be converted to a MIME type and copied).

This section outlines how the grid fits in with native operating system drag and drop. It is assumed the reader is familiar with how drag and drop works. If not, refer to one of the following introductions:

- [W3C Schools](https://www.w3schools.com/html/html5_draganddrop.asp)
- [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)

> **Note**
>
> This feature should be used when you need to export Grid Data to an external application or when browser drag events need to be used because there is no way to know where content might be dropped. For all basic scenarios such as dragging data between elements in the same page or grid to grid, the grid implements its own drag and drop separate to the operating system's drag and drop. It is used internally by the grid for [Row Dragging](https://www.ag-grid.com/javascript-data-grid/row-dragging/) (for reordering rows) and for column dragging (e.g. re-ordering columns or moving columns in the [Column Tool Panel](https://www.ag-grid.com/javascript-data-grid/tool-panel-columns/)). The grid uses its own implementation in these instances as it needs finer control over the data than native browser drag & drop supports. For example, the native d&d does not provide access to the dragged item until after the drag operation is complete.

## Enable Drag Source

To allow dragging from the grid, set the property `dndSource=true` on one of the columns. This will result in the column having a drag handle displayed. When the dragging starts, the grid will by default create a JSON representation of the data and set this as MIME types `application/json` and also `text/plain`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `dndSource` | `boolean \| DndSourceCallback` |  | `false` | `boolean` or `Function`. Set to `true` (or return `true` from function) to allow dragging for native drag and drop. Module: [`DragAndDropModule`](https://www.ag-grid.com/javascript-data-grid/modules/). |

In the example below, note the following:

- The first column has `dndSource=true`, so staring a mouse drag on a cell in the first column will start a drag operation.
- When the data is dragged to the drop zone, the drop zone will display the received JSON. This is because the drop zone is programmed to accept `application/json` MIME types.
- You can also drag to other applications outside of the browser. For example, some text editors (eg Sublime Text) or word processors (eg Microsoft Word) will accept the drag based on the `text/plain` MIME type. You can test this by dragging a cell to e.g. Microsoft Word.

#### Simple

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  DragAndDropModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  DragAndDropModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
]);

const columnDefs: ColDef[] = [
  { valueGetter: "'Drag'", dndSource: true },
  { field: "id" },
  { field: "color" },
  { field: "value1" },
  { field: "value2" },
];

let gridApi: GridApi;

const gridOptions: GridOptions = {
  defaultColDef: {
    width: 80,
    filter: true,
  },
  rowClassRules: {
    "red-row": 'data.color == "Red"',
    "green-row": 'data.color == "Green"',
    "blue-row": 'data.color == "Blue"',
  },
  rowData: getData(),
  rowDragManaged: true,
  columnDefs: columnDefs,
};

function onDragOver(event: any) {
  const dragSupported = event.dataTransfer.length;

  if (dragSupported) {
    event.dataTransfer.dropEffect = "move";
  }

  event.preventDefault();
}

function onDrop(event: any) {
  const jsonData = event.dataTransfer.getData("application/json");

  const eJsonRow = document.createElement("div");
  eJsonRow.classList.add("json-row");
  eJsonRow.innerText = jsonData;

  const eJsonDisplay = document.querySelector("#eJsonDisplay")!;

  eJsonDisplay.appendChild(eJsonRow);
  event.preventDefault();
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).onDragOver = onDragOver;
  (<any>window).onDrop = onDrop;
}
```

[Live example: Simple](https://www.ag-grid.com/examples/drag-and-drop/simple/typescript)

## Dragging Between Grids

It is possible to drag rows between two instances of AG Grid. The drag is done exactly like the simple case described above. The drop is done as demonstrated in the example below.

In the example below, note the following:

- Rows can be dragged from one grid to the other grid. When the row is received, it is **not** removed from the first grid. This is the choice of the example. The example could equally have removed from the other grid.
- If the row is already present in the grid, it will not be added twice. Again this is the choice of the example.
- Rows can be removed from both grids by dragging the row to the 'Trash' drop zone.
- New rows can be created by dragging out from red, green and blue 'Create' draggable areas.

#### Two Grids

```ts
import {
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  ColDef,
  DragAndDropModule,
  GetRowIdParams,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowApiModule,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  DragAndDropModule,
  ClientSideRowModelApiModule,
  RowApiModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
]);
let rowIdSequence = 100;

const leftColumnDefs: ColDef[] = [
  { field: "id", dndSource: true },
  { field: "color" },
  { field: "value1" },
  { field: "value2" },
];

const rightColumnDefs: ColDef[] = [
  { field: "id", dndSource: true },
  { field: "color" },
  { field: "value1" },
  { field: "value2" },
];

let leftApi: GridApi;
const leftGridOptions: GridOptions = {
  defaultColDef: {
    flex: 1,
    filter: true,
  },
  rowClassRules: {
    "red-row": 'data.color == "Red"',
    "green-row": 'data.color == "Green"',
    "blue-row": 'data.color == "Blue"',
  },
  getRowId: (params: GetRowIdParams) => {
    return String(params.data.id);
  },
  rowData: createLeftRowData(),
  rowDragManaged: true,
  columnDefs: leftColumnDefs,
};

let rightApi: GridApi;
const rightGridOptions: GridOptions = {
  defaultColDef: {
    flex: 1,
    filter: true,
  },
  rowClassRules: {
    "red-row": 'data.color == "Red"',
    "green-row": 'data.color == "Green"',
    "blue-row": 'data.color == "Blue"',
  },
  getRowId: (params: GetRowIdParams) => {
    return String(params.data.id);
  },
  rowData: [],
  rowDragManaged: true,
  columnDefs: rightColumnDefs,
};

function createLeftRowData() {
  return ["Red", "Green", "Blue"].map(function (color) {
    return createDataItem(color);
  });
}

function createDataItem(color: string) {
  return {
    id: rowIdSequence++,
    color: color,
    value1: Math.floor(window.agRandom() * 100),
    value2: Math.floor(window.agRandom() * 100),
  };
}

function binDragOver(event: any) {
  const dragSupported = event.dataTransfer.types.length;

  if (dragSupported) {
    event.dataTransfer.dropEffect = "move";
    event.preventDefault();
  }
}

function binDrop(event: any) {
  event.preventDefault();

  const jsonData = event.dataTransfer.getData("application/json");
  const data = JSON.parse(jsonData);

  // if data missing or data has no id, do nothing
  if (!data || data.id == null) {
    return;
  }

  const transaction = {
    remove: [data],
  };

  const rowIsInLeftGrid = !!leftApi!.getRowNode(data.id);
  if (rowIsInLeftGrid) {
    leftApi!.applyTransaction(transaction);
  }

  const rowIsInRightGrid = !!rightApi!.getRowNode(data.id);
  if (rowIsInRightGrid) {
    rightApi!.applyTransaction(transaction);
  }
}

function dragStart(event: any, color: string) {
  const newItem = createDataItem(color);
  const jsonData = JSON.stringify(newItem);

  event.dataTransfer.setData("application/json", jsonData);
}

function gridDragOver(event: any) {
  const dragSupported = event.dataTransfer.types.length;

  if (dragSupported) {
    event.dataTransfer.dropEffect = "copy";
    event.preventDefault();
  }
}

function gridDrop(event: any, grid: string) {
  event.preventDefault();

  const jsonData = event.dataTransfer.getData("application/json");
  const data = JSON.parse(jsonData);

  // if data missing or data has no it, do nothing
  if (!data || data.id == null) {
    return;
  }

  const api = grid == "left" ? leftApi! : rightApi!;

  // do nothing if row is already in the grid, otherwise we would have duplicates
  const rowAlreadyInGrid = !!api!.getRowNode(data.id);
  if (rowAlreadyInGrid) {
    console.log("not adding row to avoid duplicates in the grid");
    return;
  }

  const transaction = {
    add: [data],
  };
  api.applyTransaction(transaction);
}

const leftGridDiv = document.querySelector<HTMLElement>("#eLeftGrid")!;
leftApi = createGrid(leftGridDiv, leftGridOptions);

const rightGridDiv = document.querySelector<HTMLElement>("#eRightGrid")!;
rightApi = createGrid(rightGridDiv, rightGridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).binDragOver = binDragOver;
  (<any>window).binDrop = binDrop;
  (<any>window).dragStart = dragStart;
  (<any>window).gridDragOver = gridDragOver;
  (<any>window).gridDrop = gridDrop;
}

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).binDragOver = binDragOver;
  (<any>window).binDrop = binDrop;
  (<any>window).dragStart = dragStart;
  (<any>window).gridDragOver = gridDragOver;
  (<any>window).gridDrop = gridDrop;
}
```

[Live example: Two Grids](https://www.ag-grid.com/examples/drag-and-drop/two-grids/typescript)

Note that there is no specific drop zone logic in the grid. This was done on purpose after analysis.

On initial analysis, consideration was given to exposing callbacks or firing events in the grid for the drop zone relevant events e.g. `onDragEnter`, `onDragExit` etc. However this did not add any additional value given that the developer can easily add such event listeners to the grid div directly.

Given that the grid would be simply exposing the underlying events / callbacks rather than doing any processing itself, it would not be adding any value and so providing such callbacks would just be adding a layer of useless logic.

## Custom Drag Data

It is possible that a JSON representation of the data is not what is required as the drag data.

To provide alternative drag data, use the `dndSourceOnRowDrag` callback on the column definition. This allows specific processing by the application for the `rowdrag` even rather than the default grid behaviour.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `dndSourceOnRowDrag` | `DndSourceOnRowDragFunc` |  |  | Function to allow custom drag functionality for native drag and drop. Module: [`DragAndDropModule`](https://www.ag-grid.com/javascript-data-grid/modules/). |

The example below is identical to the first example on this page with the addition of custom drag data. Note the following:

- The draggable column also has `dndSourceOnRowDrag` set.
- The `onRowDrag` method provides an alternative piece of drag data to be set into the drag event.
- The data dragged also includes row state such as whether the rows is selected or not.

#### Custom Drag Data

```ts
import {
  ClientSideRowModelModule,
  DndSourceOnRowDragParams,
  DragAndDropModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  DragAndDropModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
]);

let gridApi: GridApi;

const gridOptions: GridOptions = {
  defaultColDef: {
    width: 80,
    filter: true,
  },
  rowClassRules: {
    "red-row": 'data.color == "Red"',
    "green-row": 'data.color == "Green"',
    "blue-row": 'data.color == "Blue"',
  },
  rowData: getData(),
  rowDragManaged: true,
  columnDefs: [
    {
      valueGetter: "'Drag'",
      dndSource: true,
      dndSourceOnRowDrag: onRowDrag,
    },
    { field: "id" },
    { field: "color" },
    { field: "value1" },
    { field: "value2" },
  ],
};

function onDragOver(event: any) {
  const dragSupported = event.dataTransfer.types.length;

  if (dragSupported) {
    event.dataTransfer.dropEffect = "move";
  }

  event.preventDefault();
}

function onDrop(event: any) {
  event.preventDefault();
  const jsonData = event.dataTransfer.getData("application/json");

  const eJsonRow = document.createElement("div");
  eJsonRow.classList.add("json-row");
  eJsonRow.innerText = jsonData;

  const eJsonDisplay = document.querySelector("#eJsonDisplay")!;
  eJsonDisplay.appendChild(eJsonRow);
}

function onRowDrag(params: DndSourceOnRowDragParams) {
  // create the data that we want to drag
  const rowNode = params.rowNode;
  const e = params.dragEvent;
  const jsonObject = {
    grid: "GRID_001",
    operation: "Drag on Column",
    rowId: rowNode.data.id,
    selected: rowNode.isSelected(),
  };
  const jsonData = JSON.stringify(jsonObject);

  e.dataTransfer!.setData("application/json", jsonData);
  e.dataTransfer!.setData("text/plain", jsonData);
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).onDragOver = onDragOver;
  (<any>window).onDrop = onDrop;
}
```

[Live example: Custom Drag Data](https://www.ag-grid.com/examples/drag-and-drop/custom-drag-data/typescript)

## Custom Drag Component

Drag and drop is a complex application-level requirement. As such, a component (the grid) can't propose a drag and drop solution that is appropriate for all applications. For this reason, if the application has drag and drop requirements, you would likely want to implement a custom [Cell Renderer](https://www.ag-grid.com/javascript-data-grid/component-cell-renderer/) specifically for your needs.

The example below shows a custom drag and drop cell renderer. Note the following:

- The dragging works similar to before, rows are dragged from the left grid to the right drop zone.
- The grid does not provide the dragging. Instead, the example's cell renderer implements the drag logic.

#### Custom Drag Component

```ts
import {
  ClientSideRowModelModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";
import { DragSourceRenderer } from "./dragSourceRenderer";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
]);

const rowClassRules = {
  "red-row": 'data.color == "Red"',
  "green-row": 'data.color == "Green"',
  "blue-row": 'data.color == "Blue"',
};

let gridApi: GridApi;

const gridOptions: GridOptions = {
  defaultColDef: {
    width: 80,
    filter: true,
  },
  rowClassRules: rowClassRules,
  rowData: getData(),
  rowDragManaged: true,
  columnDefs: [
    { cellRenderer: DragSourceRenderer, minWidth: 100 },
    { field: "id" },
    { field: "color" },
    { field: "value1" },
    { field: "value2" },
  ],
};

function onDragOver(event: any) {
  const types = event.dataTransfer.types;

  const dragSupported = types.length;

  if (dragSupported) {
    event.dataTransfer.dropEffect = "move";
  }

  event.preventDefault();
}

function onDrop(event: any) {
  event.preventDefault();

  const textData = event.dataTransfer.getData("text/plain");
  const eJsonRow = document.createElement("div");
  eJsonRow.classList.add("json-row");
  eJsonRow.innerText = textData;

  const eJsonDisplay = document.querySelector("#eJsonDisplay")!;
  eJsonDisplay.appendChild(eJsonRow);
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).onDragOver = onDragOver;
  (<any>window).onDrop = onDrop;
}
```

[Live example: Custom Drag Component](https://www.ag-grid.com/examples/drag-and-drop/custom-drag-comp/typescript)
