This is my first attempt at a reusable function for creating tooltips on D3 charts.
Built with blockbuilder.org
forked from TommyCoin80's block: Reusable D3 Tooltip
xxxxxxxxxx
<meta charset="utf-8">
<head>
<link href='https://fonts.googleapis.com/css?family=Play' rel='stylesheet' type='text/css'>
<style>
body {
margin:auto;
font-family: 'Play', sans-serif;
}
text {
font-family: 'Play', sans-serif;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="tooltip.js"></script>
</head>
<body>
</body>
<script>
// Dummy Data for the chart
var data = [
{name:'A',count:64,description:"This is column A!"},
{name:'B',count:32,description:"This is column B!"},
{name:'C',count:16,description:"This is column C!"},
{name:'D',count:8,description:"This is column D!"},
{name:'E',count:4,description:"This is column E!"},
{name:'F',count:2,description:"This is column F!"},
];
// Draw a basic bar chart
var margin = {top:20, left:50, bottom:50, right:20};
var height = 500 - margin.top - margin.bottom,
width = 960 - margin.left - margin.right;
var svg = d3.select("body")
.append("svg")
.attr("height", height + margin.top + margin.bottom)
.attr("width", width + margin.left + margin.right)
.style("cursor","default")
.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand()
.domain(data.map(function(d) { return d.name;}))
.range([0,width])
.padding(.1);
var y = d3.scaleLinear()
.domain([0,70])
.range([height,0]);
var color = d3.scaleOrdinal(d3.schemeCategory10)
.domain(x.domain())
var tooltip = d3.tooltip() // returns the tooltip function
.extent([[0,0],[width,height]]) // tells the tooltip how much area it has to work with
.tips(["name","description"],["Bar Name: ","Description: "]) // tells the tooltip which properties to display in the tip and what to label thme
.fontSize(12) // sets the font size for the tooltip
.padding([8,4]) // sets the amount of padding in the tooltip rectangle
.margin([10,10]); // set the distance H and V to keep the tooltip from the mouse pointer
svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("x", function(d) { return x(d.name)})
.attr("y", function(d) { return y(d.count)})
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.count)})
.attr("fill", function(d) { return color(d.name)})
.each(tooltip.events); // attaches the tooltips mouseenter/leave/move events but does not overwrite previously attached events
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
svg.append("g")
.call(d3.axisLeft(y));
svg.call(tooltip) // draws the tooltip;
</script>
https://d3js.org/d3.v4.min.js