user1855009
user1855009

Reputation: 971

Trying to append a click function to the node text in d3

I'm trying to generate a modal with information pulled from my json file when the text of a node is clicked on. I'm having trouble, so I'm just trying to generate an alert box at the moment. I think that I need to declare a variable for the node text, but I'm having trouble. Here is what I have right now:

  node.append("svg:text")
  .attr("text-anchor", "middle")
  .attr("dy", "3.5em")
  .text(function(d) { return d.name; })

  var textNodes = node.append("svg:text").text()
  .on("click", function(d, i) { alert("Hello world"); });

Or this, I don't see why this wouldn't work either.

node.append("svg:text")
  .attr("text-anchor", "middle")
  .attr("dy", "3.5em")
  .text(function(d) { return d.name; })
  .on("click", function(d) { alert("Hello world"); });

Upvotes: 4

Views: 7869

Answers (3)

rashidotm
rashidotm

Reputation: 444

to expand on the topic, the following function

d3.event.stopPropagation();

will make the node not expand or collapse if you clicked on the text but the node will continue to expand and collapse if you clicked on the node circle next to the name. Pretty neat.

Upvotes: 0

Roy Segall
Roy Segall

Reputation: 334

I managed to do do recogize a click on the label using something like this:

    const text = this.g.selectAll('text')
  .data(nodes)
  .enter().append('text')
    .attr('class', 'label')
    .style('fill-opacity', function(d) { return d.parent === root ? 1 : 0; })
    .style('display', function(d) { return d.parent === root ? 'inline' : 'none'; })
    .style('pointer-events', 'auto')
    .on("click", function(d) {
      d3.event.stopPropagation();
      console.log(d.data.name);
    })
    .text(function(d) { return d.data.name});

Upvotes: 3

nrabinowitz
nrabinowitz

Reputation: 55678

You are explicitly setting pointer-events: none for the text nodes (maybe a copy and paste error). Removing this line in the styles allows the click event to fire.

Upvotes: 10

Related Questions