Search code examples
svgsvg-animate

Animated SVG: animate on click only works when clicking on border


I'm trying to make an SVG with two animations that make coloured boxes appear to highlight text. See below for a minimal example.

Currently, the text is placed in front of the coloured box, because the text gets very dim if I do this the other way around (not so badly in this example, because text is black, but more so with other colours). But now there is only a very small border of the coloured box that can be clicked. I'd like the entire box to be clickable, but the text to be placed in front of the colour. Is there a way to do this?

<svg
  version="1.1"
  baseProfile="full"
  width="110" height="30"
  xmlns="http://www.w3.org/2000/svg">
  
  <rect id="redbox" x="0" y="0" width="110" height="30" rx="4" ry="4" style="fill:red;stroke:none;fill-opacity:0" />
  
  <animate xlink:href="#redbox" attributeType="CSS" attributeName="fill-opacity" 
           from="0" to="0.5" dur="1s" begin="click" fill="freeze"/>
  <rect x="5" y="5" width="100" height="20" rx="4" ry="4" fill="none" stroke="black" />
  
  <text dominant-baseline="central" font-size="11px">
    <tspan x="10" y="14.5">Highlight on click</tspan>
  </text>
  
</svg>

.


Solution

  • Just make the text pointer-events="none" Then mouse clicks will go through to the parent which is what you want.

    <svg
      version="1.1"
      baseProfile="full"
      width="110" height="30"
      xmlns="http://www.w3.org/2000/svg">
      
      <rect id="redbox" x="0" y="0" width="110" height="30" rx="4" ry="4" style="fill:red;stroke:none;fill-opacity:0" />
      
      <animate xlink:href="#redbox" attributeType="CSS" attributeName="fill-opacity" 
               from="0" to="0.5" dur="1s" begin="click" fill="freeze"/>
      <rect x="5" y="5" width="100" height="20" rx="4" ry="4" fill="none" stroke="black" />
      
      <text dominant-baseline="central" pointer-events="none" font-size="11px">
        <tspan x="10" y="14.5">Highlight on click</tspan>
      </text>
      
    </svg>