Search code examples
javascriptd3.jsdagre-d3

Why is my click event on my dynamically added D3 node not firing?


My code adds a node dynamically through the user to create a force directed graph.

My problem is that my click event isn't getting fired after I add a node:

//change the node's colour to blue when clicked
d3.select("svg").selectAll("g.node").on("click", function(OperationName) {
  debugger;
  OperationArray = JSON.parse(localStorage['dynamicNode']);
  var rect = this.firstChild;
  changeColour(rect);
  document.getElementById('selectedOperation').value = OperationName;
  document.getElementById('previousOperation').value = OperationArray[OperationName].inputQueue
  document.getElementById('nextOperation').value = nextOperation;
});

If I try running this piece of code in the console after I add a node, the click event gets fired and the node changes colour but it doesn't work in the browser by itself.

From what I understand I am supposed to run my click event after I load the graph but how do I do that here? I want to be able to fire my click event at any time once I add a node so I can add more operations to it later.

Working Demo: here

In case you use the demo:

  1. The operation I select from the "Select an Operation" drop down gets added when I keep the previous and next operations to "NONE".

  2. Once I add the first node, I add the other nodes while mentioning the previous node and keeping the next node as 'NONE'.

  3. If I want to add a node in the middle I mention both the previous node and the next node if they exist.


Solution

  • The answer was really simple and I got the idea from this answer here I just had to paste that piece of code inside my draw function where everything was rendering so that it gets bound again.