Mathew Shaji
Mathew Shaji

Reputation: 23

How to display a text when mouseover a cilcle

I have tried a code but it dosent work properly. Can you suggest a method to resolve the error. I am new to Visualization and at the beginning stage of d3.js

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">    </script>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">

var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);    

sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function()    {d3.select(this).append("text").attr("fill","blue").text("fill aliceblue");})


 </script>
 </body>
 </html>

Upvotes: 2

Views: 55

Answers (2)

Ivan Jovović
Ivan Jovović

Reputation: 5298

As suggested here: https://stackoverflow.com/a/16780756/1023562

Create a tooltip div and attach it to mouseover, mousemove and mouseout events.

var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");}); 

Working fiddle: https://jsfiddle.net/vc95wcvm/

Note that in this Fiddle I have loaded http://d3js.org/d3.v2.js in the script panel (because Fiddle refuses to load it over http, it requires https), so the code that interests you is at the bottom of script panel.

Upvotes: 0

DavidDomain
DavidDomain

Reputation: 15303

Your are trying to append the text element to the circle, which is not possible. Create a group element and add your circle and text elements to that group. Here is an example.

var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);    

var grp = sampleSVG.append("g");

var circle = grp.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50);

circle.on("mouseover", function() {
      grp.append("text")
        .style("fill", "black")
        .attr("x", 32)
        .attr("y", 52)
        .text("Hello");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="viz"></div>

Upvotes: 2

Related Questions