ctrlaltdel
ctrlaltdel

Reputation: 685

SVG: show/hide text or textArea on hover

I'm using clipPath to apply different "masking" effects to images on a page.

Each image will have a caption of variable length. Upon hovering over the image, I want to show the caption on top of the image and on mouseout, I want to hide the caption. Because of the varying caption length, I need the text to wrap appropriately, so that the text doesn't go outside the image.

I've experimented with using foreignObject and textArea, but I couldn't seem to get the hover effect working properly.

I also attempted to use plain HTML (specifically, a paragraph tag) and absolute positioning + z-index to position the text, but the text size didn't scale with the image's size accordingly (because it wasn't part of the SVG).

I'm using jQuery in this project, so if a JS solution is needed, jQuery is available.

Here's the HTML that I'm working with (and a jsFiddle if needed):

<div class="featured-image" id="featured-image-one">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
    <defs>
      <clipPath id="ellipse">
        <ellipse fill="#ff0000" cx="50" cy="35.5" rx="49.5" ry="35" />
      </clipPath>
      <clipPath id="hexagon">
        <polygon points="25, 0  75, 0 100, 43.30127018922193 75, 86.60254037844386  25, 86.60254037844386  0, 43.30127018922193"/>
      </clipPath>
      <clipPath id="rectangle">
        <rect x="0" y="0" width="100" height="70"></rect>
      </clipPath>
    </defs>
    <g>
      <image preserveAspectRatio="none" x="0" y="0" width="100%" height="100%" xlink:href="http://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Bucephala-albeola-010.jpg/800px-Bucephala-albeola-010.jpg" id="clippy" clip-path="url(#hexagon)" />
      <foreignObject x="10" y="30" width="100" height="100" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
        <body xmlns="http://www.w3.org/1999/xhtml">
          <p style="color: #ffffff; font-size: 5px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </body>
      </foreignObject>
    </g>
  </svg>
</div>​

Upvotes: 4

Views: 4515

Answers (1)

acjay
acjay

Reputation: 36551

Check this out: http://jsfiddle.net/LgAjd/4/

Basically I just added an id to your foreignObject and styled its display to be none, so it's invisible by default, and then used jQuery event bindings to handle the hover condition.

Javascript code:

$hoverText = $('#hoverText');
$('body').on('mouseover', '#featured-image-one', function () {
    $hoverText.show();
});
$('body').on('mouseout', '#featured-image-one', function () {
    $hoverText.hide();
});

Upvotes: 3

Related Questions