score:7

Accepted answer

Just add the svg text node as the last element to the svg element, so it will render on top of all the other elements. Then you can listen to the scroll event on your content div and adjust the y attribute of the text node.

Here is an example.

var content = document.getElementById('viz');

var svg = d3.select("#viz")
.append("svg")
.attr("width", 300)
.attr("height", 300);
svg.append("rect")
  .style("stroke", "green")
  .style("fill", "green")
  .attr("x", 50)
  .attr("y", 25)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "yellow")
  .style("fill", "yellow")
  .attr("x", 50)
  .attr("y", 50)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "green")
  .style("fill", "green")
  .attr("x", 50)
  .attr("y", 75)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "yellow")
  .style("fill", "yellow")
  .attr("x", 50)
  .attr("y", 100)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "green")
  .style("fill", "green")
  .attr("x", 50)
  .attr("y", 125)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "yellow")
  .style("fill", "yellow")
  .attr("x", 50)
  .attr("y", 150)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "green")
  .style("fill", "green")
  .attr("x", 50)
  .attr("y", 175)
  .attr("width", 25)
  .attr("height", 25);
svg.append("rect")
  .style("stroke", "yellow")
  .style("fill", "yellow")
  .attr("x", 50)
  .attr("y", 200)
  .attr("width", 25)
  .attr("height", 25);
var label = svg.append("text")
.attr("x", 40)
.attr("y", 10)
.attr("dy", ".35em")
.text("LABEL");

content.addEventListener('scroll', function(evt) {
  label.node().setAttribute('y', 10 + this.scrollTop);
}, false)
.container{
  float:left;
  height: 250px;
  width:250px; 
  padding:3px; 
  background:#FFA500;
}
.content{
  height:224px;
  overflow:auto;
  background:#FFFFFF;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<div class="container">
  <div id="viz" class="content"></div>            
</div>


Related Query