I am working with a d3 scatterplot and I want my tooltip to appear beside a dot when I mouse over that dot. I know this is very simple but I don't know where I have gone wrong! This is the relevant code.It throws this error:
Uncaught TypeError: Cannot read property 'pageX' of null
If anyone could point me in the right direction I would be very grateful as I am new to d3! Thanks in advance.
// add the tooltip area to the webpage
var tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
function mouseHandler (d) {
d3.json("connection3.php?paperID="+d.ID, function(error,data) {
var authorList = ""
data.forEach(function(d) {
authorList = authorList + d.AUTHOR;
console.log(authorList);
})
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(authorList)
.style("left",(d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
}
css:
.tooltip {
position: absolute;
width: 200px;
height: 28px;
pointer-events: none;
background: lightsteelblue;
}
The lines:
.style("left",(d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
would work well if they were directly inside the mousehandler function. However, they are within a callback function for d3.json, so it would explain why d3.event is no longer defined.
So try to save the values of pageX and pageY to local variables before calling d3.json.
function mouseHandler (d) {
var pageX=d3.event.pageX;
var pageY=d3.event.pageY;
d3.json("connection3.php?paperID="+d.ID, function(error,data) {
var authorList = ""
data.forEach(function(d) {
authorList = authorList + d.AUTHOR;
console.log(authorList);
})
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(authorList)
.style("left",(pageX) + "px")
.style("top", (pageY - 28) + "px");
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With