How can I change the color of an SVG image on hover?

32,260

Solution 1

SVG Files can be modified directly from javascript, i.e. properties of the "image" are accessible from within the DOM.

Look at this post from stack overflow: modify stroke and fill of svg image with javascript

It's important to remember that to do so, you cannot enclose the svg file in the common HTML <img/> tag, use instead the <svg>...</svg> as shown in the post.

EDIT: svg on w3schools

I added a link to w3schools so you can see more properties of the svg object

Have Fun

Solution 2

If you need to do hover effects in svg you shouldn't use <img> tags. Instead reference the svg with an <iframe>, <object> or <embed> tag. If you want to save a http GET request you can put the svg markup inline in the html document.

Here's an example showing a simple fill hover effect inside an svg, and another one (slightly more complex that creates an outline on hover using a filter). Anyway, it's basically about applying a :hover CSS rule to set the fill color.

An example with all of the above ways of using svg can be seen here.

Share:
32,260
Kenmore
Author by

Kenmore

Updated on June 05, 2020

Comments

  • Kenmore
    Kenmore almost 4 years

    Possible Duplicate:
    Changing SVG image color with javascript

    I'd like to change the fill of an SVG image when I hover over it.

    Right now I have a black question mark exported from Illustrator to SVG. I can put on my page with the img tag and it displays fine, however I have no idea how to change the color in code.

  • Erik Dahlström
    Erik Dahlström over 11 years
    image replacement is a very ineffecient way to change a hover fill color (for the svg case).
  • Kaleab Woldemariam
    Kaleab Woldemariam over 6 years
    the svg on w3schools gives 404 (page not found).
  • danie7L T
    danie7L T almost 5 years
    The Link has been updated