You are here

Example of simple jsTree with drag and drop

Submitted by Asif Nowaj, Last Modified on 2019-11-18

If you haven’t read the introductory post on jsTree, I would recommend reading the Example of simple jsTree with static JSON data.

There is a very little change to make the jsTree work with drag and drop feature. jsTree has multiple plugins to enable different features. In this case, we will use “dnd” plugin to enable drag and drop feature. If you are looking for jstree drag and drop example then you are at the right place.

Once context menu is added as a plugin, you will get the below default menu.

Simple jsTree Outcome

Do not forget to make “check_callback” as true to work with the this feature action.

My example of the simple jsTree is below. I have highlighted the important piece of information that is tricky.

Simple JSTree

Code file is below, so that you copy it and can be tested.


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Simple jsTree</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
    <script type="text/javascript">
        $(function () {

            var jsondata = [
                           { "id": "ajson1", "parent": "#", "text": "Simple root node" },
                           { "id": "ajson2", "parent": "#", "text": "Root node 2" },
                           { "id": "ajson3", "parent": "ajson2", "text": "Child 1" },
                           { "id": "ajson4", "parent": "ajson2", "text": "Child 2" },
            ];

            createJSTree(jsondata);
        });

        function createJSTree(jsondata) {            
            $('#SimpleJSTree').jstree({
                "core": {
                    "check_callback": true,
                    'data': jsondata
                },
                "plugins": ["dnd"]
            });
        }
    </script>
</head>
<body>
    <div id="SimpleJSTree"></div>
</body>
</html>

The outcome will be like below when dragging “Child 2” node into “Child 1”.
Simple jsTree Outcome

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.

https://forum.everyething.com/jstree-f33/