Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add hover tooltip for line in svg

I am trying to add simple hover text for two lines in SVG. I have included it as a 'title' in the code below but nothing happens when I hover over either line. Since they cross, I don't particularly care what it says when you hover over the intersection.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <script data-require="[email protected]" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  <style type="text/css">
  </style>
</head>

<body>
  <script type="text/javascript">
    //Width and height
    var w = 500;
    var h = 300;
    var padding = 30;


    //Create SVG element
    var svg = d3.select("body")
      .append("svg")
      .attr("width", w)
      .attr("height", h)
      .attr("background-color", "green")

      svg.append("rect")
        .attr("width", w)
        .attr("height", h)
        .attr("fill", "green");

      svg.append("line")
        .attr("x1", 30)
        .attr("y1", 40)
        .attr("x2", 80)
        .attr("y2", 90)
        .attr("stroke", "blue")
        .attr("stroke-width", 2)
        .attr("title", "This is a blue line");

      svg.append("line")
        .attr("x1", 30)
        .attr("y1", 90)
        .attr("x2", 80)
        .attr("y2", 40)
        .attr("stroke", "red")
        .attr("stroke-width", 2)
        .attr("title", "This is a red line");

  </script>
</body>

</html>
like image 269
garson Avatar asked Oct 22 '25 16:10

garson


1 Answers

With SVG you want a title child element, not a title attribute.

  svg.append("line")
    .attr("x1", 30)
    .attr("y1", 40)
    .attr("x2", 80)
    .attr("y2", 90)
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .append("title").text("This is a blue line");
like image 172
Robert Longson Avatar answered Oct 25 '25 06:10

Robert Longson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!