Skip to content
  1. Examples

Click

This example shows how to implement click interraction with nodes and edges. It uses the on method to listen to the click event and displays informations about the clicked element.

ts
import Ogma from '@linkurious/ogma';

const ogma = new Ogma({
  container: 'graph-container'
});

ogma.events.on('click', evt => {
  const target = evt.target,
    button = evt.button, // can be "left", "middle" or "right"
    x = evt.x,
    y = evt.y;

  let clickTarget;
  if (!target) {
    clickTarget = 'background';
  } else {
    clickTarget = (target.isNode ? 'node' : 'edge') + ' ' + target.getId();
  }
  document.getElementById('info')!.textContent =
    clickTarget + ' clicked ' + button + ' at (' + x + ',' + y + ')';
});

ogma.styles.addNodeRule({
  text: {
    content: n => 'Node ' + n.getId()
  }
});

ogma.styles.addEdgeRule({
  text: {
    content: e => 'Edge ' + e.getId()
  }
});

ogma.generate
  .random({ nodes: 5, edges: 10 })
  .then(g => ogma.setGraph(g))
  .then(() => ogma.view.locateGraph());
html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <link type="text/css" rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div id="graph-container"></div>
    <div id="info" class="info">Click on a node or an edge</div>
    <script type="module" src="index.ts"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}
.info {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 100;
  padding: 1em;
  color: rgba(255, 255, 255, 1);
  background: rgba(0, 90, 200, 1);
  border-radius: 5px;
  min-width: 20%;
  font-family: Georgia, 'Times New Roman', Times, serif;
  pointer-events: none;
}