Hide edge labels in vis.js-network

969 Views Asked by At

I would like to simply show/hide the labels of the edges of my vis.js-network - is this possible?

I have tried to update the edges in the vis.js-data structure:

  • Delete the label property - doesn't work
  • Set the label to undefined - doesn't work
  • Set the label to '' - doesn't work
  • Set the label to ' ' - works

I would prefer a network-wise toggle of some kind, but I haven't found one.

Is there a better way of doing this?

1

There are 1 best solutions below

1
Chris C On

An alternative to updating the label property on each edge is to change the font color to be transparent for all edges. The setOptions() method can be used to update the options and will apply all edges in the network. The options edges.font.color and edges.font.strokeColor should both be updated, then returned to their original values to display the edges.

Example below and also at https://jsfiddle.net/rk9s87ud/.

var 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" },
]);

var edges = new vis.DataSet([
  { from: 1, to: 2, label: 'Edge 1' },
  { from: 2, to: 3, label: 'Edge 2' },
  { from: 3, to: 4, label: 'Edge 3' },
  { from: 4, to: 5, label: 'Edge 4' },
]);

var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges,
};

var options = {
  nodes: {
    // Set any other options, for example node color to gold
    color: 'gold'
  },
  edges: {
    font: { 
      // Set to the default colors as per the documentation
      color: '#343434',
      strokeColor: '#ffffff'
    }
  }
}

var hiddenEdgeTextOptions = {
  edges: {
    font: {
      // Set the colors to transparent
      color: 'transparent',
      strokeColor: 'transparent'
    }
  }
};

var network = new vis.Network(container, data, options);

var displayLabels = true;
document.getElementById('toggleLabels').onclick = function() {
  if(displayLabels){
    // Apply options for hidden edge text
    // This will override the existing options for text color
    // This does not clear other options (e.g. node.color)
    network.setOptions(hiddenEdgeTextOptions);
    displayLabels = false;
  } else {
    // Apply standard options
    network.setOptions(options);
    displayLabels = true;
  }
}
#mynetwork {
  width: 600px;
  height: 160px;
  border: 1px solid lightgray;
}
<script src="https://visjs.github.io/vis-network/standalone/umd/vis-network.min.js"></script>
<button id="toggleLabels">Toggle labels</button>
<div id="mynetwork"></div>