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.
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"});
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With