Dinesh K
Dinesh K

Reputation: 651

Add Edge Dynamically visjs

Can anyone help me with adding edges dynamically in this visjs network? Actually, I am trying to use drag and drop to add nodes to the canvas, but I need help adding edges when I click the node and add edge dynamically to another node existing on canvas.

Upvotes: 8

Views: 14186

Answers (4)

pgoldweic
pgoldweic

Reputation: 467

You can use the vis.js 'update' function to add either nodes or edges dinamycally. You simply pass in an array with the set of either nodes or edges that you are trying to add. You call it like this:

nodes.update(updateNodesArray)

OR

edges.update(updateEdgesArray)

where nodes and edges are the vis.DataSet instances that you originally created for the network.

Full docs can be found at https://visjs.github.io/vis-data/data/dataset.html

Upvotes: 11

Sijo  Song
Sijo Song

Reputation: 151

var network = new vis.Network(container, datas, options)
//And then
network.addEdgeMode();

You can create edges on drag & drop

Upvotes: 3

Henrik
Henrik

Reputation: 2229

The intention of this answer is to help my self stop googling it, as I apparently keeps forgetting the solution, and keeps ending up here first...

It is also technically an answer to the question:

function AddEdge(from_id, to_id)
{
    network.body.data.edges.add([{from: from_id, to: to_id}])
}

It works as the network data node is a vis dataset, and updating it (also via the add/remove methods) will update the render as well.

Upvotes: 8

TERMIN
TERMIN

Reputation: 862

check this example from visjs. http://visjs.org/examples/network/other/manipulation.html

you can custom the way of adding\editing\deleting by configure your network as follow:

manipulation: {
        enabled: false,
          addNode: function (data, callback) {
              // filling in the popup DOM elements
              console.log('add', data);
          },
          editNode: function (data, callback) {
              // filling in the popup DOM elements
              console.log('edit', data);
          },
          addEdge: function (data, callback) {
              console.log('add edge', data);
              if (data.from == data.to) {
                  var r = confirm("Do you want to connect the node to itself?");
                  if (r === true) {
                      callback(data);
                  }
              }
              else {
                  callback(data);
              }
          }
      }

Upvotes: 1

Related Questions