Yan Yi
Yan Yi

Reputation: 773

d3 treat text and circle as one object

I've got some circles with text on them on a force layout. Tooltips are generated using d3-tip.

The problem is that even though I grouped both text and circle under one group, events like mouseover and click are still treating the two as separate objects.

When I hover over the text in the circle, a tooltip is shown. When I move my cursor out of the text (but still within the circle), the same tooltip is re-generated and shown, but in a slightly different position.

Is there any way I can make the two objects behave as one? I'm aiming for a seamless transition so the user is unaware that the two are separate objects.

Left: Mouse over circle Right: Mouse over text

enter image description here enter image description here

 var tip = d3.tip()
        .attr("class", "d3-tip")
        .html(function(d) {return d["ModuleTitle"];});

    var vis = d3.select("body")
        .append("svg")
        .call(tip);

    var elem = svgContainer.selectAll("g")
        .data(nodesData);

    var elemEnter = elem.enter()
        .append("g")
        .on('mouseover', tip.show)
        .on('mousedown', tip.hide)
        .on('mouseout', tip.hide);

    var circle = elemEnter.append("circle")
        .attr("r", function(d) {return d.radius;})
        .style("fill", function(d, i) { return color(i % 20);})
        .call(force.drag);


    var text = elemEnter.append("text")
        .attr("text-anchor", "middle")
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d) {return d.fontsize;})
        .attr("fill", "black")
        .text(function(d) {return d["ModuleCode"];});

Upvotes: 0

Views: 62

Answers (1)

Elijah
Elijah

Reputation: 4639

If you don't want your text to trigger events you should set its pointer-events style to none. You can do this in css:

 text {
  pointer-events: none;
 }

Or with D3 when you're creating the elements:

var text = elemEnter.append("text")
    .attr("text-anchor", "middle")
    .attr("font-family", "sans-serif")
    .attr("font-size", function(d) {return d.fontsize;})
    .attr("fill", "black")
    .style("pointer-events", "none")
    .text(function(d) {return d["ModuleCode"];});

Upvotes: 3

Related Questions