0

I am using Cytoscape JS to create a web browser-based graph manipulation tool. I am facing a problem in listening the drag event of multiple selection of nodes.

I could listen to 'drag' event of nodes using the following code:

cy.on('drag', 'node', function (e) {
  let draggedNode = e.target
  ...
}

However, when I drag several nodes at once, the event is triggered to all selected nodes individually.

What I want to accomplish is to listen to drag event of a node where several nodes are currently selected, but only listen to the element directly (including only the one node directly under the cursor or the user’s finger). So that whenever I drag multiple selected nodes at once, the event only triggered to the one that being dragged under the finger or cursor only.

This is similar to grabon, freeon dragfreeon events that is currently available to CytoscapeJS. However, there is no dragon event for this. I don't want to listen to drag event of all currently selected node events. But only the one that is currently under the cursor/finger.

I have been trying to find the cursor position from the passed e parameter, so that I can test whether the cursor is currently over the current triggering node or not. However the position and renderedPosition attributes values were found to be undefined. So I can't do the cursor position test.

Therefore, is someone out there know how to implement this in Javascript? Thank you.

1 Answer 1

3

You could use grabon, free or similar to detect the target, add a class to it, and listen to drag events only for nodes of that class.

The item.isNode() check in the code below is kinda pointless.

cy.on('grabon', 'node', (e) => {
    let item = e.target;

    if (item.isNode()) {
        item.addClass('drag-parent');
    }
});

cy.on('free', 'node', (e) => {
    let item = e.target;

    if (item.isNode() && item.hasClass('drag-parent')) {
        item.removeClass('drag-parent');
    }
})

cy.on('drag', 'node.drag-parent', (e) => {
    let item = e.target;

    console.warn(item.id());
})
1
  • 1
    I never thought that programmatically adding class to a node is possible that way. It's a working implementation alternative to dragon event which is not currently exists. One thing to note is to make sure that the additional code on grabon, free, drag event listener don't interfere with current existing implementation, especially if you are trying to implement complex functionality. Thanks.
    – Aryo
    Apr 25, 2020 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.