Attaching multiple events
Attaching tooltip and highlight
by christopheviau
HTML
<script src="http://mbostock.github.com/d3/d3.js"></script>
JavaScript
var data = d3.range(10).map(Math.random);
var w = 400,
h = 200,
barW = w / data.length-10,
barH = function(d, i){return d / d3.max(data) * h;},
barX = function(d, i){return i / data.length * w;},
barY = function(d, i){return h - barH(d);};
var tooltip = tooltipEvents(function(d, i){return d;});
var highlight = highlightEvents();
d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("width", barW)
.attr("height", barH)
.attr("x", barX)
.attr("y", barY)
.call(eventBatch(tooltip, highlight));
function highlightEvents(){
var oldColor = null;
return{
mouseover: function(d, i){
var element = d3.select(this);
oldColor = element.style('fill');
var brighterColor = d3.rgb(oldColor).brighter();
element.style('fill', brighterColor);
},
mouseout: function(d, i){
var element = d3.select(this);
element.style('fill', oldColor);
}
};
}
function tooltipEvents(accessor){
var tooltipDiv,
bodyNode = d3.select('body').node();
return{
mouseover: function(d, i){
d3.select('body').selectAll('div.tooltip').remove();
tooltipDiv = d3.select('body').append('div').attr('class', 'tooltip');
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style('left', (absoluteMousePos[0] + 10)+'px')
.style('top', (absoluteMousePos[1] - 15)+'px')
.style('position', 'absolute')
.style('z-index', 1001);
var tooltipText = accessor(d, i) || '';
tooltipDiv.style('width', function(d, i){return (tooltipText.length > 80) ? '300px' : null;})
.html(tooltipText);
},
mousemove: function(d, i) {
var absoluteMousePos = d3.mouse(bodyNode);
tooltipDiv.style('left',...