DevExtreme v23.2 is now available.

Explore our newest features/capabilities and share your thoughts with us.

Your search did not match any results.

Drag & Drop for Hierarchical Data Structure

This sample app demonstrates node drag and drop operations within DevExtreme TreeView when using a hierarchical data structure. You can reorder nodes within a single tree view or drag and drop nodes between two separate tree views.

Use Sortable to implement the necessary drag and drop functionality within your web app. The following steps outline configuration requirements for our JavaScript TreeView:

  1. Allow users to reorder nodes
    Wrap the TreeView in a Sortable and enable the Sortable's allowReordering property.

  2. Allow users to change node hierarchy
    Enable the allowDropInsideItem property so that users can drop one node onto another. This adds it as the target node's child. If this property is disabled, users can only drop nodes between other nodes.

  3. Allow users to drag only tree view nodes
    To specify tree view nodes as drag targets, set the filter property to a class selector. Since all tree view nodes use the dx-treeview-node class, you can use this class selector as needed.

  4. Prevent a node from being moved into its child node
    When a user moves a parent node into its own child node, it breaks the hierarchy. To prevent this outcome, implement the onDragChange function and traverse up the node tree. If the target is a child of the dragged node, cancel the ability to drop the node.

  5. Reorder nodes in code
    Implement the onDragEnd function. In this function, you must gather information about nodes being moved. With this information, you can reorder the nodes in the data source (see the moveNode function), and reassign the data source to the TreeView's items property.

  6. Specify tree view identifiers (for drag and drop between multiple tree views only)
    Identifiers help distinguish between multiple tree views. Save them in the Sortable's data property. The tree views below include the following identifiers: "driveC" and "driveD".

  7. Combine tree views into one drag and drop group (for drag and drop between multiple tree views only)
    Set the Sortable's group property to the same value for all tree views. This allows users to move nodes between the tree views.

Backend API
$(() => { createTreeView('#treeviewDriveC', itemsDriveC); createTreeView('#treeviewDriveD', itemsDriveD); createSortable('#treeviewDriveC', 'driveC'); createSortable('#treeviewDriveD', 'driveD'); }); function createTreeView(selector, items) { $(selector).dxTreeView({ items, expandNodesRecursive: false, dataStructure: 'tree', width: 250, height: 380, displayExpr: 'name', }); } function createSortable(selector, driveName) { $(selector).dxSortable({ filter: '.dx-treeview-item', data: driveName, group: 'shared', allowDropInsideItem: true, allowReordering: true, onDragChange(e) { if (e.fromComponent === e.toComponent) { const $nodes = e.element.find('.dx-treeview-node'); const isDragIntoChild = $nodes.eq(e.fromIndex).find($nodes.eq(e.toIndex)).length > 0; if (isDragIntoChild) { e.cancel = true; } } }, onDragEnd(e) { if (e.fromComponent === e.toComponent && e.fromIndex === e.toIndex) { return; } const fromTreeView = getTreeView(e.fromData); const toTreeView = getTreeView(e.toData); const fromNode = findNode(fromTreeView, e.fromIndex); const toNode = findNode(toTreeView, calculateToIndex(e)); if (e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) { return; } const fromTopVisibleNode = getTopVisibleNode(e.fromComponent); const toTopVisibleNode = getTopVisibleNode(e.toComponent); const fromItems = fromTreeView.option('items'); const toItems = toTreeView.option('items'); moveNode(fromNode, toNode, fromItems, toItems, e.dropInsideItem); fromTreeView.option('items', fromItems); toTreeView.option('items', toItems); fromTreeView.scrollToItem(fromTopVisibleNode); toTreeView.scrollToItem(toTopVisibleNode); }, }); } function getTreeView(driveName) { return driveName === 'driveC' ? $('#treeviewDriveC').dxTreeView('instance') : $('#treeviewDriveD').dxTreeView('instance'); } function calculateToIndex(e) { if (e.fromComponent !== e.toComponent || e.dropInsideItem) { return e.toIndex; } return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1; } function findNode(treeView, index) { const nodeElement = treeView.element().find('.dx-treeview-node')[index]; if (nodeElement) { return findNodeById(treeView.getNodes(), nodeElement.getAttribute('data-item-id')); } return null; } function findNodeById(nodes, id) { for (let i = 0; i < nodes.length; i += 1) { if (nodes[i].itemData.id === id) { return nodes[i]; } if (nodes[i].children) { const node = findNodeById(nodes[i].children, id); if (node != null) { return node; } } } return null; } function moveNode(fromNode, toNode, fromItems, toItems, isDropInsideItem) { const fromNodeContainingArray = getNodeContainingArray(fromNode, fromItems); const fromIndex = findIndex(fromNodeContainingArray, fromNode.itemData.id); fromNodeContainingArray.splice(fromIndex, 1); if (isDropInsideItem) { toNode.itemData.items.splice(toNode.itemData.items.length, 0, fromNode.itemData); } else { const toNodeContainingArray = getNodeContainingArray(toNode, toItems); const toIndex = toNode === null ? toItems.length : findIndex(toNodeContainingArray, toNode.itemData.id); toNodeContainingArray.splice(toIndex, 0, fromNode.itemData); } } function getNodeContainingArray(node, rootArray) { return node === null || node.parent === null ? rootArray : node.parent.itemData.items; } function findIndex(array, id) { const idsArray = array.map((elem) => elem.id); return idsArray.indexOf(id); } function getTopVisibleNode(component) { const treeViewElement = component.element().get(0); const treeViewTopPosition = treeViewElement.getBoundingClientRect().top; const nodes = treeViewElement.querySelectorAll('.dx-treeview-node'); for (let i = 0; i < nodes.length; i += 1) { const nodeTopPosition = nodes[i].getBoundingClientRect().top; if (nodeTopPosition >= treeViewTopPosition) { return nodes[i]; } } return null; }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>DevExtreme Demo</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script>window.jQuery || document.write(decodeURIComponent('%3Cscript src="js/jquery.min.js"%3E%3C/script%3E'))</script> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/23.2.5/css/dx.light.css" /> <script src="js/dx.all.js"></script> <script src="data.js"></script> <link rel="stylesheet" type="text/css" href="styles.css" /> <script src="index.js"></script> </head> <body class="dx-viewport"> <div class="demo-container"> <div class="form"> <div class="drive-panel"> <div class="drive-header dx-treeview-item" ><div class="dx-treeview-item-content"><i class="dx-icon dx-icon-activefolder"></i><span>Drive C:</span></div></div > <div id="treeviewDriveC"></div> </div> <div class="drive-panel"> <div class="drive-header dx-treeview-item" ><div class="dx-treeview-item-content"><i class="dx-icon dx-icon-activefolder"></i><span>Drive D:</span></div></div > <div id="treeviewDriveD"></div> </div> </div> </div> </body> </html>
.form { display: flex; } .form > div { display: inline-block; vertical-align: top; } #treeviewDriveC, #treeviewDriveD { margin-top: 10px; } .dx-treeview-item { box-sizing: border-box; } .drive-header { min-height: auto; padding: 0; cursor: default; } .drive-panel { padding: 20px 30px; font-size: 115%; font-weight: bold; border-right: 1px solid rgba(165, 165, 165, 0.4); height: 100%; } .drive-panel:last-of-type { border-right: none; }
const itemsDriveD = []; const itemsDriveC = [{ id: '1', name: 'Documents', isDirectory: true, icon: 'activefolder', expanded: true, items: [{ id: '2', name: 'Projects', isDirectory: true, icon: 'activefolder', expanded: true, items: [{ id: '3', name: 'About.rtf', icon: 'file', isDirectory: false, }, { id: '4', name: 'Passwords.rtf', icon: 'file', isDirectory: false, }, ], }, { id: '5', name: 'About.xml', icon: 'file', isDirectory: false, }, { id: '6', name: 'Managers.rtf', icon: 'file', isDirectory: false, }, { id: '7', name: 'ToDo.txt', icon: 'file', isDirectory: false, }], }, { id: '8', name: 'Images', isDirectory: true, icon: 'activefolder', expanded: true, items: [{ id: '9', name: 'logo.png', icon: 'file', isDirectory: false, }, { id: '10', name: 'banner.gif', icon: 'file', isDirectory: false, }, ], }, { id: '11', name: 'System', isDirectory: true, icon: 'activefolder', expanded: true, items: [{ id: '12', name: 'Employees.txt', icon: 'file', isDirectory: false, }, { id: '13', name: 'PasswordList.txt', icon: 'file', isDirectory: false, }], }, { id: '14', name: 'Description.rtf', icon: 'file', isDirectory: false, }, { id: '15', name: 'Description.txt', icon: 'file', isDirectory: false, }, ];