Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding input text box on clicking the data labels d3.js

I am trying to implement annotations on my scatterplot using d3.js v3. I want to insert a text box when I click on the text labels on my chart. For which I wrote this code:

circleGroup.selectAll("text")
           .data(data)
           .enter()
           .append("text")
           .text(function (d) {
            if (d.label) {
                 return d.label;
             }
             return "";
            })
           .attr("x", function (d) {
               return x(d.time) + 6;
           })
           .attr("y", function (d) {
               return y(d.plotY) + 4;
            })
           .attr("font-size", "10px")
           .attr("fill", "#2d3d45")
           .on("click", function(d) {
               d3.select(this).append("input").attr("type", "text").attr("name", "textInput").attr("value", "Text goes here");

           });

The selection of the text element is working correctly. Its just not popping text box when i click on the text labels. Where am i going wrong? Is my approach not in right direction ?

like image 332
user2128 Avatar asked Oct 27 '25 10:10

user2128


1 Answers

You cannot append html element into svg. The only way to do it - use foreignObject element.

The foreignObject SVG element allows for inclusion of a foreign XML namespace which has its graphical content drawn by a different user agent. The included foreign graphical content is subject to SVG transformations and compositing.

Look at the very simplified example:

var texts = ['foo', 'bar'];

var container = d3.select('g');

container
	.selectAll('text')
  .data(texts)
  .enter()
  .append('text')
  .text(function(d) { return d; })
  .attr('y', function(d,i) { return 50 * i })
  .on('click', function(d,i) {
    container
      .append("foreignObject")
      .attr("x", 0)
      .attr("y", function() { return 50 * i })
      .attr("width", 140)
      .attr("height", 20)
      .html(function(d) {
        return '<input type="text" value="Text goes here" />'
      })
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div style="font-size: 12px;">Click on the texts below:</div>
<svg width="300" heigth="400">
  <g transform="translate(20, 20)">
  </g>
</svg>
like image 176
Mikhail Shabrikov Avatar answered Oct 29 '25 00:10

Mikhail Shabrikov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!