Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 00:19
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/1087001 to your computer and use it in GitHub Desktop.
Absolute-Positioned Tooltip
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 12px;
padding: 8px;
margin-top: -20px;
font: 10px sans-serif;
background: #ddd;
pointer-events: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("transform", "translate(480,50) rotate(60) scale(2)")
.append("rect")
.attr("width", 140)
.attr("height", 140)
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseout", mouseout);
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("display", "none");
function mouseover() {
div.style("display", "inline");
}
function mousemove() {
div
.text(d3.event.pageX + ", " + d3.event.pageY)
.style("left", (d3.event.pageX - 34) + "px")
.style("top", (d3.event.pageY - 12) + "px");
}
function mouseout() {
div.style("display", "none");
}
</script>
@srinivmw
Copy link

Can we apply anything instead of

   .style("left", (d3.event.pageX - 34) + "px")
  .style("top", (d3.event.pageY - 12) + "px"); 

because when i use this the tooltip is not displaying in its position correctly.....

Below two things also not working:
1)

          .style("left", d3.select(this).attr("cx") + "px")     
          .style("top", d3.select(this).attr("cy") + "px");
           .style("left", dx + "px")     
      .style("top", dy + "px");

Can i have good solution for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment