All versions of this documentation
X

Custom selection

This example demonstrates the implementation of a new selection mechanism based on capturing events on nodes. Left-clicking a node sets it as the selection, right-clicking adds to it and left clicking the background clears the selection.

Open in a new window.
          <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../build/ogma.min.js"></script>
  <style>
    #graph-container { top: 0; bottom: 0; left: 0; right: 0; position: absolute; margin: 0; overflow: hidden; }
  </style>
</head>
<body>
  <div id="graph-container"></div>

<script>
'use strict';


function randomGraph(N, E) {
  var g = {nodes:[], edges:[]};

  for (var i = 0; i < N; i++) {
    g.nodes.push({
      id: 'n' + i,
      attributes: {
        x: Math.random() * 100,
        y: Math.random() * 100,
        radius: 3
      },
      data: {
        age: Math.random()*10
      }
    });
  }
  for (var i = 0; i < E; i++) {
    g.edges.push({
      id: 'e' + i,
      source: 'n' + (Math.random() * N | 0),
      target: 'n' + (Math.random() * N | 0)
    });
  }
  return g;
}

// Create a random graph
var g = randomGraph(10, 10);

// Initialize Ogma
var ogma = new Ogma({
  graph: g,
  container: 'graph-container',
  // Deactivate the default selection mode.
  options: {
    interactions: {
      selection: {
        enabled: false
      }
    }
  }
});

// Or deactivate the default selection mode dynamically
// ogma.setOptions({ interactions: { selection: { enabled: false }} });

// Define a new selection mechanism

ogma.events.onClick(function (event) {
  var button = event.button,
      target = event.target;

  if (!target) {
    // If no node/edge is clicked, clear the selection regardless of the button used

    ogma.clearSelection();
    console.log('selection cleared');
  } else if (button === 'left') {
    // If a node or edge is left clicked, we clear the selection and set the clicked node/edge as the selection

    ogma.clearSelection();
    target.setSelected(true);

    console.log('selection set to: ', ogma.getSelectedNodes().getId().join());
  } else if (button === 'right') {
    // If a node or edge is right clicked, we add it to the selection

    target.setSelected(true);
    console.log('selection expanded: ', ogma.getSelectedNodes().getId().join());
  }
});

</script>
</body>
</html>