Search code examples
labelzoomingvis.js-network

Can labels be hidden by default, but shown when the node is selected?


I want my graph has no label by default, but when I select a node its label will show up. There is chosen.label that seems promising, but I still don't know how to write the function. There is also a question about scaling.label, but as indicated in there it also seems not working.

Another approach is to have a checkbox to turn on and off the labels. See: Can the filter in the configure option specify an only option?


Solution

  • This can be achieved using the chosen.label option in combination with the transparent font color.

    In the options object firstly set the default font color for nodes to transparent, then within chosen.label adjust it to a visible color.

    var options = {
      nodes: {
        font: {
          // Set default label font color to transparent
          color: "transparent"
        },
        chosen: {
          label: function(values, id, selected, hovering) {
            // Adjust label font color so it is visible
            // Updates to the values object are applied to the network
            values.color = "#343434";
          }
        }
      }
    };
    

    Working example is below.

    // create an array with nodes
    var nodes = new vis.DataSet([
      { id: 1, label: "Node 1" },
      { id: 2, label: "Node 2" },
      { id: 3, label: "Node 3" }
    ]);
    
    // create an array with edges
    var edges = new vis.DataSet([
      { from: 1, to: 3 },
      { from: 1, to: 2 },
      { from: 3, to: 3 },
    ]);
    
    // create a network
    var container = document.getElementById("mynetwork");
    var treeData = {
      nodes: nodes,
      edges: edges,
    };
    var options = {
      nodes: {
        font: {
          // Set default label font color to transparent
          color: "transparent"
        },
        chosen: {
          label: function(values, id, selected, hovering) {
            // Adjust label font color so it is visible
            // Updates to the values object are applied to the network
            values.color = "#343434";
          }
        }
      }
    };
    var network = new vis.Network(container, treeData, options);
    #mynetwork {
      width: 600px;
      height: 180px;
      border: 1px solid lightgray;
    }
    <script src="https://visjs.github.io/vis-network/standalone/umd/vis-network.min.js"></script>
    <div id="mynetwork"></div>