Changing SVG image color with javascript

Potney Switters picture Potney Switters · Mar 26, 2012 · Viewed 207k times · Source

I am trying to alter svg image colors with javascript. Is this possible? Can I load it as an object and then somehow have access to the color/image-data.

Every respone or tip is highly appreciated!

Answer

peter picture peter · Mar 26, 2012

Sure, here is an example (standard HTML boilerplate omitted):

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">
  <circle id="circle1" r="30" cx="34" cy="34" 
            style="fill: red; stroke: blue; stroke-width: 2"/>
  </svg>
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>