ggPeti
ggPeti

Reputation: 875

How can I create an info box in HTML that shows information relevant to a hovered SVG path?

I have an SVG with a couple paths that describe regions, like this:

<svg>
    <g>
        <path d="..."></path>
        <path d="..."></path>
        <path d="..."></path>
    </g>
</svg>

And I'd like to display a div based on which path is hovered. I tried putting the respective divs inside the paths in order to be able to do this in the css:

path:hover div.infobox
{
    display: block
}

div.infobox
{
    display: none
    position: absolute
}

But that doesn't work, because the SVG is not rendered properly if I hide non SVG elements in it.

Is there an easy way to do this by CSS or with jQuery?

Upvotes: 0

Views: 9051

Answers (2)

Thomas W
Thomas W

Reputation: 15371

If a simple title tooltip would do, then you can use SVG's title element (that does the same thing as an HTML title attribute):

<svg>
  <g>
    <path d="..."><title>text 1</tile></path>
    <path d="..."><title>text 2</tile></path>
    <path d="..."><title>text 3</tile></path>
  </g>
</svg>

You could also use SVG text:

<svg>
  <style type="text/css">
    text {display:none}
    svg > g > g:hover text {display:inline}
  </style>
  <g>
    <g>
      <path d="..."/>
      <text>text 1</text>
    </g>
    <g>
      <path d="..."/>
      <text>text 2</text>
    </g>
    <g>
      <path d="..."/>
      <text>text 3</text>
    </g>
  </g>
</svg>

You'd of course have to position the text properly and possibly add a background, either using a filter, as described in this anwer, or a rect.

Upvotes: 1

Lenny
Lenny

Reputation: 5939

in jQuery it should just be...

$("path").on("hover", function() {
    $(".infobox").toggle();
});

And just create the div somewhere on the page (outside of the svg) with absolute position.

If you need to do it for a specific SVG it might be better to do

$("#svg-id").find("path").on("hover", function() {
    $(".infobox").toggle();
});

Update for related path / div

SVG:

<path id="infobox1">...</path>
<path id="infobox2">...</path>
...

HTML:

<div class="infobox infobox1">...</div>
<div class="infobox infobox2">...</div>
...

Javascript:

$("#svg-id").find("path").on("hover", function() {
    //hide all info boxes
    $(".infobox").hide();
    //show the right one based on id - class relation
    $("."+$(this).attr('id')).show();
});

Upvotes: 1

Related Questions