Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing SVG styles from javascript

I have an SVG map of the world, and I want to colour each region by various metrics in real time by altering style attributes for each region in the svg. For example, I want to tint the UK blue.

This needs to be dynamic as the data changes often and is pushed out to the browser.

like image 338
Chilly Avatar asked Mar 17 '10 14:03

Chilly


2 Answers

You can apply CSS styling to SVG Elements. Needless to say, this requires a suitable markup. So for instance, if your map looks something like (VERY simplified :-)

<svg>
    <g id="USA">...</g>
    <g id="UK">...</g>
</svg>

You could simply do the following:

var country = document.getElementById("UK");
country.setAttribute("style", "fill: blue; stroke: black");

Of course it is also possible to embed stylesheets into an SVG document:

<svg>
  <defs>
    <style type="text/css">
      <![CDATA[
      // insert CSS rules here
      ]]>
    </style>
  </defs>
</svg>

And finally, it is also possible to include an external stylesheet into an SVG document:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet href="style.css" type="text/css"?>
<svg>
    ...
like image 120
Leo Avatar answered Oct 18 '22 15:10

Leo


I case you don't want to change the whole style, you can do:

var country = document.getElementById("UK");
country.style.fill = "blue";
country.style.stroke = "black";
like image 33
mjaque Avatar answered Oct 18 '22 14:10

mjaque