Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js Tooltip positioning not working

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;

}

like image 217
Paul Smith Avatar asked Mar 04 '16 10:03

Paul Smith


1 Answers

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");                            
        })
        }  
like image 92
tarulen Avatar answered Oct 17 '22 00:10

tarulen