I am new to d3.js and coding in general. This is my question:
I am trying to find a way to break long displayed names of force layout objects in lines.
I believe this example on jsfiddle solves your problem.
The code is actually your example, just a little bit modified.
There is a new function wordwrap2() that takes care of proper splitting of the names:
function wordwrap2( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
Then, there is a new important part of the code that, instead of just creating one text label per node, creates this:
var maxLength = 20;
var separation = 18;
var textX = 0;
nodeEnter.append("text")
.attr("dy", "0.3em")
.each(function (d) {
var lines = wordwrap2(d.name, maxLength).split('\n');
console.log(d.name);
console.log(lines);
for (var i = 0; i < lines.length; i++) {
d3.select(this)
.append("tspan")
.attr("dy", separation)
.attr("x", textX)
.text(lines[i]);
}
});
(variable maxLength - length used for criterium for splitting names)
(variable separation - visual vertical distance between split lines of a name)
For example this would be the output for maxLength=20:
This would be the output for maxLength=15: (notice that Aspect Ratio Banker became Aspect Ratio/Banker)
This would be the output for maxLength=10: (now, check out Aspect/Ratio/Banker !)
And this would be the output for maxLength=10 and separation=30 (a little more space between individual lines):