jsTree - drag and drop to/from external sources
by vaibhav saxena
October 17, 2019
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="jstree"></div>
<p>
Select this text and drag into the tree to create a node
</p>
<p>
Or drag this link: <a href="https://google.com">Google</a>
</p>
<div id="dragTarget">
<h3>Drag Nodes To/From The Big Blue Circle</h3>
</div>
CSS
@import url(//fonts.googleapis.com/css?family=Roboto:400,400italic,700,700italic|Cabin+Condensed:600);
body{
font-family: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: normal;
}
.jstree-default-responsive .jstree-anchor {
font-weight: 400;
}
#jstree {
margin: 1em 0;
font-size: 1.1em;
line-height: normal;
font-weight: 400;
}
#dragTarget {
margin: 1em;
padding: 1em;
width: 500px;
height: 500px;
background-color: skyblue;
text-align: center;
border-radius: 50%;
}
h3 {
margin: 4em auto;
}
p {
font-family: "Cabin Condensed";
font-size: 1.3em;
margin: 1em 0;
}
JavaScript
var theTree = [
{
"id": "animal",
"parent": "#",
"text": "Animals",
"data": {
"name": "Quick"
},
"type": "root"
},
{
"id": "device",
"parent": "#",
"text": "Devices",
"type": "root"
},
{
"id": "dog",
"parent": "animal",
"text": "Dogs",
"type": "file"
},
{
"id": "lion",
"parent": "animal",
"text": "Lions",
"type": "file"
},
{
"id": "mobile",
"parent": "device",
"text": "Mobile Phones",
"type": "file"
},
{
"id": "lappy",
"parent": "device",
"text": "Laptops",
"type": "file"
},
{
"id": "doberman",
"parent": "dog",
"text": "Doberman"
},
{
"id": "dalmation",
"parent": "dog",
"text": "Dalmatian"
},
{
"id": "schnauzer",
"parent": "dog",
"text": "Schnauzer"
},
{
"id": "african",
"parent": "lion",
"text": "African Lion"
},
{
"id": "indian",
"parent": "lion",
"text": "Indian Lion",
"data": {
"lastName": "Silver"
}
},
{
"id": "apple",
"parent": "mobile",
"text": "Apple iPhone"
},
{
"id": "samsung",
"parent": "mobile",
"text": "Samsung Galaxy"
},
{
"id": "lenovo",
"parent": "lappy",
"text": "Lenovo"
},
{
"id": "hp",
"parent": "lappy",
"text": "HP"
}
],
draggedDiv = null,
old_currentTarget = null,
old_onselectstart,
old_unselectable,
shorten = function(text, options, maxLength = 32) {
if (text.length <= maxLength) {
return text;
}
if (!options) options = {};
var defaultOptions = {
suffix: true,
suffixString: " …",
preserveWordBoundaries: true,
wordSeparator: " "
};
$.extend(options, defaultOptions);
var suffix = '';
if (text.length > maxLength && options.suffix) {
suffix = options.suffixString;
}
var maxTextLength = maxLength - suffix.length,
cutIndex,
lastWordSeparatorIndex;
...