1

I'm trying to create a legend that shows a color block, the name corresponding to that color, and a dropdown to change the color. Here is my code:

function create_legend(){
    var legend = legendSVG.selectAll("g.legend")
    .data(ext_color_domain)
    .enter().append("g")
    .attr("class", "legend");

    var ls_w = 20, ls_h = 20;

    //create color blocks
    legend.append("rect")
    .attr("x", 20)
    .attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
    .attr("width", ls_w)
    .attr("height", ls_h)
    .style("fill", function(d, i) { return color_scale[i]; })
    .style("opacity", 0.8);

    //create text
    legend.append("text")
    .attr("x", 50)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .text(function(d, i){ return segment_map[i]; });

    //create dropdown for colors
    legend.append("div")
    .append("select")
    .attr("x", 80)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
    .data(color_names)
    .enter().append("option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; });      

}

The color & text appears, but the dropdown element does not.

enter image description here

Update: Ok, I tried doing the following but it gives me the error "Uncaught SyntaxError: Unexpected token"

'//create dropdown for colors
    legend.append("foreignObject")
    .attr("class", ".dropdown")
    .append("div")
    .append("select")
    .attr("x", 80)
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
    .data(color_names)
    .enter().append("option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; });'
NBC
  • 1,606
  • 4
  • 18
  • 31

2 Answers2

0

In SVG a html element can only be the child of a foreignObject element and a foreignObject element cannot be the child of a text element. A foreignObject element can be the sibling of a text element though so your DOM needs to look something like this.

g
|-   rect
|-   text
|-   foreignObject
        |- div
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
0

For foreign object you should be appending the element like this: .append("xhtml:div") instead of .append("div")

corrected full snippet.

 legend.append("foreignObject")
    .attr("class", ".dropdown")
    .append("xhtml:div")
    .append("xhtml:select")
    .attr("width", 80)

    .attr("x",function(d, i){ return width * i})
    .attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
    .selectAll("option")
     .data(color_names)
    .enter().append("xhtml:option")
    .attr("value", function (d) { return d; })
    .text(function (d) { return d; } 
Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55