Reputation: 1284
This experiment is based on the Health & Wealth of Nations example. I'm trying to have a tooltip-style label show up and float above each of the dots when the mouse hovers over them. Each data element has a property called "name" that I'd like to display in the tooltip. For the sake of brevity I omitted most of the irrelevant code.
// Create all the dots, one for each data point.
var dot = svg.append("g")
.attr("class", "dots")
.selectAll(".dot")
.data(myData)
.enter().append("circle")
.attr("class", "dot")
.call(position)
.call(enableInteraction)
.sort(order);
// Create a tooltip element.
var tooltip = svg.append("text")
.attr("class", "tooltip");
// Assign each of the dots the various mouse events.
function enableInteraction(dot) {
dot.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("mousemove", mousemove);
function mouseover() {
tooltip.text(???); // How do I get the name into here?
}
function mouseout() {
tooltip.text("");
}
function mousemove() {
var cursor = d3.mouse(this);
tooltip.attr("x", cursor[0] + 5)
.attr("y", cursor[1] + 5);
}
}
I tried using a function to retrieve the name and pass it into enableInteraction() as follows:
.call(enableInteraction, function(d) { return d.name; } )
but the function object is being passed instead of its return value.
So how do I get each data element's name to display in the tooltip?
Upvotes: 3
Views: 2771
Reputation: 102743
You could use a currying technique to get that info into your mouseover event handler. I'm unsure of the syntax for getting the name, but this is the idea:
// this function returns a function
function moveoverHandler(dot) {
return function mouseover() {
// I'm not sure if this is how you get the "name" property from the "dot" object
// Please update this as needed
var name = dot.data("name");
tooltip.text(name);
}
}
Then wire up the handler like this:
dot.on("mouseover", mouseover(dot));
Upvotes: 2