Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Tooltip as a d3 helper
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="./tooltip.js"></script>
</head>
<body>
<div class="viz"></div>
<script type="text/javascript">
var sampleSVG = d3.select('.viz')
.append('svg')
.attr({width: 600, height: 100});
var data = d3.range(5).map(function(d, i){ return ~~(Math.random()*100); })
sampleSVG.selectAll('circle')
.data(data)
.enter().append('circle')
.style({stroke: 'gray', fill: 'aliceblue'})
.attr({r: 40, cx: function(d, i){ return i*100 + 50; }, cy: 50})
.call(d3.helper.tooltip()
.attr({class: function(d, i) { return d + ' ' + i + ' A'; }})
.style({color: 'blue'})
.text(function(d, i){ return 'value: '+d; })
)
.on('mouseover', function(d, i){ d3.select(this).style({fill: 'skyblue'}); })
.on('mouseout', function(d, i){ d3.select(this).style({fill: 'aliceblue'}); });
</script>
</body>
</html>
d3.helper = {};
d3.helper.tooltip = function(){
var tooltipDiv;
var bodyNode = d3.select('body').node();
var attrs = {};
var text = '';
var styles = {};
function tooltip(selection){
selection.on('mouseover.tooltip', function(pD, pI){
var name, value;
// Clean up lost tooltips
d3.select('body').selectAll('div.tooltip').remove();
// Append tooltip
tooltipDiv = d3.select('body').append('div');
tooltipDiv.attr(attrs);
tooltipDiv.style(styles);
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style({
left: (absoluteMousePos[0] + 10)+'px',
top: (absoluteMousePos[1] - 15)+'px',
position: 'absolute',
'z-index': 1001
});
// Add text using the accessor function, Crop text arbitrarily
tooltipDiv.style('width', function(d, i){ return (text(pD, pI).length > 80) ? '300px' : null; })
.html(function(d, i){return text(pD, pI);});
})
.on('mousemove.tooltip', function(pD, pI){
// Move tooltip
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style({
left: (absoluteMousePos[0] + 10)+'px',
top: (absoluteMousePos[1] - 15)+'px'
});
// Keep updating the text, it could change according to position
tooltipDiv.html(function(d, i){ return text(pD, pI); });
})
.on('mouseout.tooltip', function(pD, pI){
// Remove tooltip
tooltipDiv.remove();
});
}
tooltip.attr = function(_x){
if (!arguments.length) return attrs;
attrs = _x;
return this;
};
tooltip.style = function(_x){
if (!arguments.length) return styles;
styles = _x;
return this;
};
tooltip.text = function(_x){
if (!arguments.length) return text;
text = d3.functor(_x);
return this;
};
return tooltip;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment