AmericanCities
AmericanCities

Reputation: 139

Drop down menu over d3 SVG

I'm stuck. I want to add an html drop down menu over an SVG chart that I've created using d3. Currently the drop-down menu appears below the chart, but I want the drop-down menu to appear over a specific location on the chart.

I'm unclear if my problem is with the order in which browser renders all of the elements or if it's simply an CSS issue.

Any help would be appreciated.

Here's my html:

<div class="chartArea">
  <select class = "demoSelection"></select></div>

Here's my css:

  .chartArea{
      position: relative;}

    .demoSelection {
      position: absolute;
      width: 250px;
      top:400px;
      left:250px;}

Here's where I create the SVG element in d3:

  var svg = d3.select("body").select(".chartArea")
      .append("svg")
      .attr("id","svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("class","chart");

I later populate the selection box with options in d3

  d3.select(".demoSelection")
       .append("option")
       .attr("value",demoCounter)
       .text(json.demos[demoCounter].title);

Upvotes: 3

Views: 6155

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

I don't see any mistake in the scripts you have provided.

I tried to recreate the scenario with the inputs you have provided but not able to recreate however I am putting my working code.

This might help you.

var svg = d3.select("body").select(".chartArea")
    .append("svg")
    .attr("id", "svg")
    .attr("width", 500)
    .attr("height", 500)
    .append("g").attr("class", "chart");

var data = [4, 8, 15, 16, 23, 42];

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);



var bar = svg.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

d3.select(".demoSelection")
    .append("option")
    .attr("value", 1)
    .text("Hello");
d3.select(".demoSelection")
    .append("option")
    .attr("value", 2)
    .text("Another Hello");
.chartArea {
    position: relative;
}
.demoSelection {
    position: absolute;
    width: 100px;
    top:40px;
    left:25px;
}
.chart rect {
  fill: steelblue;
}

.chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="chartArea">
    <select class="demoSelection"></select>
</div>

Upvotes: 1

Captain Nova
Captain Nova

Reputation: 31

Try adding z-index: 10; in the CSS for your demoSelection class.

Upvotes: 0

Related Questions