FirstVertex
FirstVertex

Reputation: 3784

jsTree 3: use a drag handle to restrict initiating dragging

Using jsTree 3.0.8 I want to allow nodes to be dragged and dropped within the tree, but it should only allow that action if it was initiated by a drag on a specific button or "drag handle", instead of the default behavior of allowing dragging anywhere on the row.

I populate my tree via Html and for each node I draw out a toolbar as part of that row's Html content. I assign delegated jQuery click handlers to the toolbar items. One of the toolbar items needs to have a move icon and only allow that tree item to be moved by dragging on that toolbar button.

jQuery UI has a similar drag handle concept documented here: https://jqueryui.com/draggable/#handle

Here is one node of my tree. The "Reorder" button is where I want the user to be able to drag the row, and nowhere else.

<li data-jstree="{ 'type': 'page' }">
    <i class="jstree-icon jstree-ocl" role="presentation"></i>
    <a class="jstree-anchor" href="#" tabindex="-1" id="109_anchor">
        <i class="jstree-icon jstree-themeicon fa fa-2x fa-file font-grey-cascade jstree-themeicon-custom" role="presentation"></i>
        <div class="pull-left">
            <div class="friendly-name">test</div>
            <small>/okay/its/a/test</small>
        </div>
        <span class="nodeToolbar">
            <a title="Edit" class="passthrough btn grey-cascade btn-xs" href="/Pages/Edit/109"><i class="fa fa-pencil"></i> Edit</a>
            <a title="Preview" class="preview btn grey-cascade btn-xs" target="_pagePreview" href="/Pages/Preview/109"><i class="fa fa-eye"></i> Preview</a>
            <button title="Reorder" class="reorder btn grey-cascade btn-xs" href="#">
                <i class="fa fa-arrows"></i> Reorder
            </button>
        </span>
    </a>
</li>

I already took a look at some other solutions that involve check_callback but that seems to only prevent the move operation at the end (during the drop) rather than what I need, which is to filter the operation at the beginning (when the drag is initiated).

Upvotes: 0

Views: 1501

Answers (1)

vakata
vakata

Reputation: 3886

You will probably need to work with is_draggable: http://www.jstree.com/api/#/?q=is_dragg&f=$.jstree.defaults.dnd.is_draggable

For a quick and dirty solution - listen for mousedown touchstart events on anchor nodes and set a variable which you can then later use in the is_draggable check:

var allow_drag = false;
$('#tree').on('mousedown touchstart', '.jstree-anchor', function (e) {
  allow_drag = e.target.className.indexOf('reorder') !== -1;
});
$('#tree').jstree({
  dnd : {
    is_draggable : function () { return allow_drag; },
    ...

Upvotes: 1

Related Questions