hsluoyz
hsluoyz

Reputation: 2889

How to cursor-select SVG/d3.js text just like normal HTML text or any other text editor?

I'm using d3.js to draw a layout graph like this one: https://bl.ocks.org/mbostock/950642

But I found that it's very difficult to copy-and-paste the node's label. Take the above link as an example, I can't drag the text to select any sequence. I can only double-click the label to select a certain char sequence.

If I try to select the text with a special char like Mlle.Vaubois, I can only get Mlle or Vaubois selected, I cannot get the whole string Mlle.Vaubois selected. (See the below picture)

enter image description here

Moreover, I can't select arbitrary char sequence inside that string. For example, I can't select the middle two letters: ll inside Mlle.Vaubois. The highlighting stopped right after the first l is selected. (See below:)

enter image description here

I just want to be able to select any sequence as I want, like in a browser. For example, I can select rce La from the HTML text: Labeled Force Layout as below. Then I can Ctrl + C and Ctrl + V as I wish.

enter image description here

This issue is not just for d3.js, because another more general SVG example also has this issue: http://jsfiddle.net/wPYvS/

enter image description here

I don't know why SVG handles text selection so different with normal HTML text in a browser or any mainstream text editor? How to solve it? Thanks.

Upvotes: 1

Views: 435

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

The following example adds a click handler to all the "nodes" (ie. class="node"), which will select all the text in the node.

var nodes = document.querySelectorAll(".node");

nodes.forEach( function(elem) {
  elem.addEventListener("click", nodeClickHandler);
});

function nodeClickHandler(evt) {
  var selection = document.getSelection();
  var range = selection.getRangeAt(0);
  range.selectNode(evt.target);
}
<svg width="500" height="200">
  <g class="node" transform="translate(275.4819543667187,131.9805407488932)">
    <image xlink:href="https://github.com/favicon.ico" x="-8" y="-8" width="16" height="16"> </image>
    <text dx="12" dy=".35em">Mlle.Vaubois</text>
  </g>
</svg>

Upvotes: 3

Related Questions