d3.js - How can I set the cursor to hand when mouseover these elements on SVG container?

Saqib Ali picture Saqib Ali · Mar 31, 2016 · Viewed 24.4k times · Source

I have used d3.js to draw some circles on an SVG container.

I have successfully set the mouseover behavior on these circles to print simple console messages. I see those console messages when I mouseover (and mouseout) so I know they are working properly.

However, instead of printing that console messages, I want to change the cursor to the hand when I mouseover them, and I want to change the cursor back to the normal arrow when I mouse out. Given my code below, how can I do it?

On mouseover, I know I need to change the style property cursor to pointer and on mouseout, I know I need to change it to default but I don't know the syntax of how I should do it. Can someone please explain it to me? Below is my code.

        var myCircle = svgContainer.selectAll(".dots")
          .data(myDataList).enter().append("circle")
          .attr("class", "dots")
          .attr("cx", function(d, i) {return d.centerX})
          .attr("cy", function(d, i) {return d.centerY})
          .attr("r", 5)
          .attr("stroke-width", 0)
          .attr("fill", function(d, i) {return "red"})
          .style("display", "block");



        myCircle.on({
            "mouseover": function(d) {
              console.log('Hello World!'); // What do I change this to?
            },
            "mouseout": function(d) {
              console.log('Goodbye World!'); // What do I change this to?
            }
          }
        );

Answer

Cyril Cherian picture Cyril Cherian · Mar 31, 2016

You can do it like this:

myCircle.on({
      "mouseover": function(d) {
        d3.select(this).style("cursor", "pointer"); 
      },
      "mouseout": function(d) {
        d3.select(this).style("cursor", "default"); 
      }
    });

working code here

OR

you can simply work this out in the CSS.

myCircle.style('cursor', 'pointer')