Sometimes you need to show a tooltip over a different element than the one firing the mouseover
event. Fortunately, d3-tip allows you to do that by passing an SVGElement
as the second parameter to tip.show()
. Like this:
tip.show(data, target)
This SVGElement
will be the new target of the tooltip.
xxxxxxxxxx
<meta charset="utf-8">
<style>
rect {
stroke: #aaa;
stroke-width: 1px;
fill: #eee;
}
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="d3tip.js"></script>
<script>
var width = 960,
height = 500;
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "You're touching my " + d.name + "!";
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(100,100)");
svg.call(tip);
var data = [
{
width: 30,
height: 120,
transform: "translate(100,200)rotate(30)",
name: "right leg",
},
{
width: 30,
height: 120,
transform: "translate(140,215)rotate(-30)",
name: "left leg",
},
{
width: 40,
height: 100,
transform: "translate(115,90)",
name: "torso",
},
{
width: 60,
height: 60,
transform: "translate(105,20)",
name: "head",
},
{
width: 20,
height: 10,
transform: "translate(130,60)",
name: "mouth",
},
{
width: 10,
height: 10,
transform: "translate(115,35)",
name: "right eye",
},
{
width: 10,
height: 10,
transform: "translate(145,35)",
name: "left eye",
},
{
width: 20,
height: 90,
transform: "translate(40,40)rotate(-30)",
name: "right arm",
},
{
width: 20,
height: 90,
transform: "translate(210,35)rotate(30)",
name: "left arm",
},
];
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("id", function(d) { return d.name.replace(" ", "-") })
.attr("width", function(d) { return d.width })
.attr("height", function(d) { return d.height })
.attr("transform", function(d) { return d.transform })
.on("mouseover", function(d) { tip.show(d, document.getElementById("head")) })
.on("mouseout", tip.hide);
</script>
Modified http://d3js.org/d3.v3.min.js to a secure url
https://d3js.org/d3.v3.min.js