1

I have made a drawing of human body parts on svg and integrated it into my html :

<div id="human_body_container" style="width:145px; height: 250px;">
<svg id="human_body" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/" x="0px" y="0px"
     viewBox="0 0 145 250">
<style>
    .st0{stroke:#010101;stroke-width:0.4;stroke-miterlimit:10;}
</style>
<g id="Skull">
    <polygon id="XMLID_25_" class="st0" points="59.2,9.4 69.5,11 75.4,11 80.4,10.2 79.2,6.4 75.3,2.8 72.3,1.4 67.2,1.4 61.4,5 
    59.9,6.9 "/>
</g>
<g id="Right_ear">
    <polygon id="XMLID_24_" class="st0" points="60.7,24.7 61.3,20.7 59.7,15.9 58.7,15.9 57.5,17.5 57.5,22.2 "/>
</g>

All my poly have the class st0, here is the css :

.st0 {
fill: rgba(230,230,230, 0.5);
transition: .3s;
}

.st0:hover { 
fill: rgba(180,180,180, 1);
cursor: pointer;
}

I want to change the color of one poly only when user clicks on it, so I use the following javascript (jQuery) :

$(document).on('click', '.st0', function () {
$(this).attr('fill', 'red');
console.log('fill');
console.log($(this));
});

The click event is triggered and the poly is returned in the console, but the fill color doesn't change, any idea why and how to fix this ?

Vincent Teyssier
  • 2,146
  • 5
  • 25
  • 62

1 Answers1

1

fill is a CSS property, hence you need to set it with the css() method:

$(document).on('click', '.st0', function() {
    $(this).css('fill', 'red');
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    No problem, glad to help. – Rory McCrossan Jan 05 '16 at 11:13
  • 1
    fill is also an SVGElement presentation attribute. It's more that it's got overridden by css. http://stackoverflow.com/a/24294974/3702797 If there were no css, it would work https://jsfiddle.net/78Lb2mrp/1/ – Kaiido Jan 05 '16 at 11:52