show ingoing node on click cytoscape.js

Showing Ingoing Node on Click Cytoscape.js

As a blogger and a web developer, I have worked with Cytoscape.js to create dynamic and interactive network graphs. One of the essential features of any network graph is to be able to click on a node and see its incoming connections. In this post, I will walk you through the steps of displaying the ingoing node on click in Cytoscape.js.

Step 1: Add Event Listener

The first step is to add an event listener to the node that we want to click. We can do this by using the cy.on() function. Here is an example:


cy.on('tap', 'node', function(event) {
  var targetNode = event.target;
  console.log('Clicked node:', targetNode.id());
});

In this example, we are listening for the tap event on all nodes. When the event is triggered, we get a reference to the clicked node using event.target. We then log the ID of the clicked node to the console.

Step 2: Get Incoming Edges

Now that we have a reference to the clicked node, we can use it to get its incoming edges. We can do this by using the incomers() function. Here is an example:


var incomingEdges = targetNode.incomers();
console.log('Incoming edges:', incomingEdges);

In this example, we are using the incomers() function to get all the incoming edges of the clicked node. We then log the incoming edges to the console.

Step 3: Display Incoming Nodes

Finally, we can use the incoming edges to get the incoming nodes and display them. We can do this by using the connectedNodes() function. Here is an example:


var incomingEdges = targetNode.incomers();
var incomingNodes = incomingEdges.connectedNodes();
console.log('Incoming nodes:', incomingNodes);

In this example, we are using the connectedNodes() function to get all the nodes that are connected to the incoming edges of the clicked node. We then log the incoming nodes to the console.

To display the incoming nodes, we can add a new element to the DOM and populate it with the incoming node data. Here is an example:


var incomingEdges = targetNode.incomers();
var incomingNodes = incomingEdges.connectedNodes();

var nodeData = '';
incomingNodes.forEach(function(node) {
  nodeData += '<li>' + node.id() + '</li>';
});

var nodeContainer = document.createElement('div');
nodeContainer.innerHTML = '<ul>' + nodeData + '</ul>';
document.body.appendChild(nodeContainer);

In this example, we are using a forEach() loop to iterate over each incoming node and create an <li> element for each one. We then add the <li> elements to a new <ul> element and append it to the DOM.

That's it! With these three steps, you can display the ingoing node on click in Cytoscape.js.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe