Editing SVG styles from javascript

I have a SVG map of the world and I want to color each region with different real-time metrics by changing the style attributes for each region in svg. EG I want the shade of blue in the UK to reflect an upcoming victory in history (um).

This should be dynamic as the data often changes and pops into the browser.

+5
source share
2 answers

You can apply CSS styles to SVG elements. Needless to say, this requires appropriate markup. For example, if your map looks something like this (VERY simplified :-)

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

You can simply do the following:

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

Of course, you can also embed stylesheets in an SVG document:

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

, , SVG:

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet href="style.css" type="text/css"?>
<svg>
    ...
+10

, , :

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

All Articles