Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vis.js: Modify node properties on click

I have an undirected graph in Vis.js and I would like to change the color and size of the adjacent nodes (scaling them according to values in a JS array) when a certain node is selected. How would I go about doing this? The documentation for vis.js network objects is unenlightening beyond the source for this example.

like image 945
manglano Avatar asked Sep 24 '15 15:09

manglano


2 Answers

You can listen for click events to know when a user clicked a node.

network.on("click", function (params) {
  console.log(params);
});

If you have creates your nodes in a DataSet, you can simply update them and Network will be automatically updated accordingly:

nodes.update({id: 4, label: "changed label"});
like image 149
Jos de Jong Avatar answered Nov 11 '22 23:11

Jos de Jong


Elaborating on this answer in response to this question. The vis.js->Network documentation has all the details, you just have to put them in order.

You use the "on" method of the network instance in order to listen for events. See "Method Reference -> Global" at the link above. This "on" method takes two inputs. The first is the event to be listened for; the second is a function that specifies the action to be taken when the event occurs.

To understand how to use this information, see the "Events" section in the documentation link above. For click events, your code will look something like

network.on("click", function (params) {
  console.log(params);
});

The first argument is always a string; in this case we are interested in the "click" event. The second argument is a callback function that takes a single argument (I called this argument "params" in the example above). The "Events" documentation (again, see link above) summarizes this structure for you. Specifically, if the click event is associated with a node, then the ID of the node that was clicked is accessible as params.nodes[0].

Back to the original question. To change the color of adjacent nodes, you first need an array of the adjacent nodes. You do this using the "getConnectedNodes" method (see "Method Reference -> Information" at the link above). This will give you an array of node IDs. Next, for each ID in that array, you need to update the properties you wish to change.

The easiest way to update node properties is to create your nodes using a DataSet. You are probably already doing so. See this example, and notice the lines

var nodes = new vis.DataSet([...]);

This nodes variable has its own update method. So if you have (e.g.,) a variable CurrentID that holds the node ID of a node you wish to modify, and you want to (e.g.,) change the label of that node to the text string stored in another variable newLabel, you would do

nodes.update({id:CurrentID, label:newLabel});
like image 26
Clay Avatar answered Nov 12 '22 00:11

Clay