Resizing Diagrams

Sometimes it may be necessary to resize the div that contains a GoJS Diagram. GoJS does not listen or attempt to detect changes in the div's size, so you must manually tell each Diagram when you perform an action that resizes its containing div.

Using Diagram.requestUpdate to resize a Div

The following example has a button that enlarges the Diagram's div. When it is clicked, the div is visibly resized but the Diagram remains the same size.

    // A minimal Diagram
    diagram.nodeTemplate =
      $(go.Node, "Auto",
        $(go.Shape, "RoundedRectangle",
          new go.Binding("fill", "color")),
        $(go.TextBlock,
          { margin: 3 },  // some room around the text
          new go.Binding("text", "key"))
      );

    diagram.model = new go.GraphLinksModel(
    [
      { key: "Alpha", color: "lightblue" },
      { key: "Beta", color: "orange" },
      { key: "Gamma", color: "lightgreen" },
      { key: "Delta", color: "pink" }
    ],
    [
      { from: "Alpha", to: "Beta" },
      { from: "Alpha", to: "Gamma" },
      { from: "Gamma", to: "Delta" },
      { from: "Delta", to: "Alpha" }
    ]);

    // Resize the diagram with this button
    var button1 = document.getElementById('button1');
    button1.addEventListener('click', function() {
      var div = diagram.div;
      div.style.width = '200px';
    });

This button won't work:

Typically we will want the Diagram to resize to its div at the same time that the div resizes. To do this we add a call to Diagram.requestUpdate after we have resized the div. This checks to see if the Diagram's div has changed size, and if so, redraws the diagram at the appropriate new dimensions.

Below is nearly identical code, except that a call to Diagram.requestUpdate has been added.

    // A minimal Diagram
    diagram.nodeTemplate =
      $(go.Node, "Auto",
        $(go.Shape, "RoundedRectangle",
          new go.Binding("fill", "color")),
        $(go.TextBlock,
          { margin: 3 },  // some room around the text
          new go.Binding("text", "key"))
      );

    diagram.model = new go.GraphLinksModel(
    [
      { key: "Alpha", color: "lightblue" },
      { key: "Beta", color: "orange" },
      { key: "Gamma", color: "lightgreen" },
      { key: "Delta", color: "pink" }
    ],
    [
      { from: "Alpha", to: "Beta" },
      { from: "Alpha", to: "Gamma" },
      { from: "Gamma", to: "Delta" },
      { from: "Delta", to: "Alpha" }
    ]);

    // Resize the diagram with this button
    var button2 = document.getElementById('button2');
    button2.addEventListener('click', function() {
      var div = diagram.div;
      div.style.width = '200px';
      diagram.requestUpdate(); // Needed!
    });