javascriptvis.js

Dragging node makes a node selected/highlighted on vis.js


Dragging a network node in vis.js library highlights/selects that node, and when drag ends the node still appears has highlighted/selected. I would like to prevent that behavior so nodes are selected only on click and not on drag, or even better on drag end to clear that highlighting. I believe it is possible through dragEnd network event but I played with it a bit with no success. Any hints?

Example for the behavior: https://visjs.github.io/vis-network/examples/network/basic_usage/legacy.html


Solution

  • This can be achieved with a combination of the dragEnd event and the unselectAll method, like:

    network.on('dragEnd', function(){
      network.unselectAll();
    });
    

    A working snippet is below:

    // create an array with nodes
    let nodes = new vis.DataSet([
      { id: 1, label: "Node 1" },
      { id: 2, label: "Node 2" },
      { id: 3, label: "Node 3" },
      { id: 4, label: "Node 4" },
      { id: 5, label: "Node 5" },
    ]);
    
    // create an array with edges
    let edges = new vis.DataSet([
      { from: 1, to: 3 },
      { from: 1, to: 2 },
      { from: 2, to: 4 },
      { from: 2, to: 5 },
      { from: 3, to: 3 },
    ]);
    
    // create a network
    const container = document.getElementById("mynetwork");
    const data = {
      nodes: nodes,
      edges: edges,
    };
    const options = {};
    const network = new vis.Network(container, data, options);
    
    // When dragging ends clear selection
    network.on('dragEnd', function(){
      network.unselectAll();
    });
    #mynetwork {
      width: 600px;
      height: 160px;
      border: 1px solid lightgray;
    }
    <script src="https://visjs.github.io/vis-network/standalone/umd/vis-network.min.js"></script>
    <div id="mynetwork"></div>

    Alternatively you could restore the previous selection when the drag ends, a sample of this can be seen at https://jsfiddle.net/ckx2apgs/.