Andy
Andy

Reputation: 950

Mouseover Effect D3.js

I have been trying to modify the examples provided by D3.js to create a step plot where I can hover over each step to get details of the value.

Currently I am looking at:

http://bl.ocks.org/mbostock/3902569

and my plot looks like:

http://jsfiddle.net/q47r3pyk/

after hours of playing with the JavaScript. It is close to my final result but if you try to hover over the points, you only get a value on the left handle side of the screen.

How do you get the hover effect to appear over where you place your mouse?

Any advice would be appreciated on what I am doing incorrectly.

My mouse over section looks like:

var focus = svg.append("g")
  .attr("class", "focus")
  .style("display", "none");

focus.append("circle")
  .attr("r", 4.5);

focus.append("text")
  .attr("x", 9)
  .attr("dy", ".35em");

svg.append("rect")
  .attr("class", "overlay")
  .attr("width", width)
  .attr("height", height)
  .on("mouseover", function() { focus.style("display", null); })
  .on("mouseout", function() { focus.style("display", "none"); })
  .on("mousemove", mousemove);

function mousemove() {
  var x0 = x.invert(d3.mouse(this)[0]),
      i = bisectDate(formatted_data, x0, 1),
      d0 = formatted_data[i - 1],
      d1 = formatted_data[i],
      d = x0 - d0.x > d1.x - x0 ? d1 : d0;
  focus.attr("transform", "translate(" + x(d.x) + "," + y(d.y) + ")");
  focus.select("text").text(d.y);

Upvotes: 0

Views: 872

Answers (1)

Pinguin Dirk
Pinguin Dirk

Reputation: 1433

I think you want to adjust your bisectDate function (as can be seen in the jsfiddle you linked).

If you use:

bisectDate = d3.bisector(function(d) { return d.x; }).left;

(using d.x instead of d.date), it's working for me.

This is due to the fact that you are storing the x coords in x (in formatted_data), whereas Mike Bostock's example uses .date. Thus, d3.bisect can't find the proper value.

Upvotes: 1

Related Questions