2

I am using a force directed graph (d3js v4), and I would like to have the text on the link. I'm using the following code for this;

    link.append("text")
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
            return "translate(" +
                ((d.source.y + d.target.y)/2) + "," + 
                ((d.source.x + d.target.x)/2) + ")";
        })
        .text(function(d) {
            console.log(d);
            console.log(d.source.x);
            return d.link_name;
        });

I only get an error with:

Error: <text> attribute transform: Expected number, "translate(NaN,NaN)".

The strange thing is when looking at my debug console the d object has a source and the x property. However when I debug the d.source.x the debug says it is undefined. Any clue what might be wrong? Here is the full code:

http://blockbuilder.org/anonymous/17bac3017a5aaab26268c4f687c302ec

Erhnam
  • 901
  • 2
  • 13
  • 23
  • 1
    Have a look at http://stackoverflow.com/questions/7389069/console-log-object-at-current-state, it will help you – Tim B Aug 02 '16 at 08:38
  • 1
    At the time of execution of the callback there are no values for `x` and `y` set on the source and target nodes. These values are initialized once the nodes are set for the simulation. In your example this happens *after* you try to position your texts, which is why you get the `NaN`s. As pointed out by @TimB you are tricked into thinking that your objects already have this values set because of the workings of `console.log()`. They are not at the time when the reference is logged, but they are when you inspect the objects afterwards. – altocumulus Aug 02 '16 at 09:18
  • Thanks for your answer. I'm aware that the object has been referenced already. That's what I also see when using the console.log(). My question is more related to how getting the x and y current values. Is this possible or not within d3js. – Erhnam Aug 02 '16 at 17:56

0 Answers0