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
<html>
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">
<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 = [
{parameter:'pH',value:64,site:"Vulcan - Vacaville"},
{parameter:'TSS',value:32,site:"Vulcan - Redbluff"},
{parameter:'Oil & Grease',value:16,site:"Vulcan - Richmond"},
{parameter:'Iron',value:8,site:"Vulcan - Redbluff"},
{parameter:'Zinc',value:4,site:"Vulcan"},
{parameter:'BOD',value:2,site:"Vulcan"},
];
//var data = d3.csv('samples.csv', function(error, data) {
// if (error) throw error;
// });
// 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.parameter;}))
.range([0,width])
.padding(.2);
var y = d3.scaleLinear()
.domain([d3.min(d3.values(data)), d3.max(d3.values(data))])
.range([height,0]);
var color = d3.scaleOrdinal(d3.schemeCategory20)
.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(["value","site"],["Parameter Value: ","Site: "]) // tells the tooltip which properties to display in the tip and what to label them
.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.parameter)})
.attr("y", function(d) { return y(d.value)})
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.value)})
.attr("fill", function(d) { return color(d.parameter)})
.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>
</html>
https://d3js.org/d3.v4.min.js