Search code examples
svgjquery-svg

svg change polygon color onclick


I have a SVG map of france in my webpage and every district is a polygon, I need that when I click a district the color change and stay that way until I click it again

this is my code

function init(evt) {
  if ( window.svgDocument == null ) {
      svgDoc = evt.target.ownerDocument;
   }

function update(district){
    $(this).find("path, polygon, circle").attr("fill", "#0d0");<- what is wrong
   }

this is one of my polygons

<path id="14" d="M82.387,173.009L109.168,141h2.42l3.33-5.965l20.425,8.818l5.296,0.475l-
 1.876,31.861l5.236,7.5v8.018 l-15.6-1.701l
 0.273-3.599C128.127,186.407,99.635,180.95,82.387,173.009z" fill="#CCCCCC"
onclick="update('14')">

as you can see Im getting the onclick event the problem is I cant get the polygon to change color.

thanks in advance.


Solution

    1. Check what this holds. A console.log(this) will make your life so much more easier
    2. I'll answer 1. This will point to the window object when a function is called. So doing a $(this).attr will find the attributes in the window object and not in the object that you expect.
    3. Since you're passing the object id in the function, you can use that to find the element in your document. You can do something like:

      $('#'+ubicacion).attr("fill","blue")
      

    Fiddle here.