Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Text Over SVG Element On Hover

So I have a simple SVG element (copied below), and I want to display text (currently within the data-label attribute) when the rectangle with the bar class is hovered over.

<svg width="511" height="15">
    <rect fill="#555555" height="15" stroke="#000000" width="510"></rect>
    <rect class="bar" x="2" y="2" width="434" height="11" fill="#97C115" data-label="Test-Label"></rect>
</svg>

There could be any number of rectangles in the SVG and the label could say anything.

Since in my situation, the entire SVG element is created in JavaScript and then printed to a HTML environment, I am able to move the label anywhere. I just want the label to appear over the rectangle or above it when hovered.

Is this at all possible, since you cannot include text within the <rect> element?

like image 927
Spedwards Avatar asked Jan 20 '17 16:01

Spedwards


2 Answers

Something like this? You can use g to group elements.

svg text {display: none;}
svg g:hover text {display: block;}
<svg width="511" height="15">
    <rect fill="#555555" height="15" stroke="#000000" width="510"></rect>
    <g>
      <rect class="bar" x="2" y="2" width="434" height="11" fill="#97C115" data-label="Test-Label"></rect>
      <text x="0" y="15">Label 1</text>
    </g>
</svg>
like image 174
shipshape Avatar answered Sep 27 '22 23:09

shipshape


Try this, I think is more convenient way to do it:

nav {
    position: absolute;
    top:-11px;
}

ul {
    position: relative;
}
nav li {
    display:inline;
}
nav a {
    display:inline-block;
    visibility: hidden;
    padding-right:5px;
    text-decoration:none;
    color: white;
}
ul li:hover a {
    visibility:visible;
}
<svg width="511" height="15">
  <rect fill="#555555" height="15" stroke="#000000" width="510"></rect>
  <rect class="bar" x="2" y="2" width="434" height="11" fill="#97C115" data-label="Test-Label"></rect>
</svg>
<nav>
  <ul>
   <li><a href="#">text_one</a></li>
   <li><a href="#">text_two</a></li>
   <li><a href="#">text_three</a></li>
  </ul>
</nav>
like image 26
Sean Bean Avatar answered Sep 27 '22 22:09

Sean Bean