Aryo
Aryo

Reputation: 4508

How to listen to drag event of CytoscapeJS node (including only the one directly under the cursor/finger)

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.

Upvotes: 1

Views: 1127

Answers (1)

Ravenous
Ravenous

Reputation: 1160

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());
})

Upvotes: 4

Related Questions