tcoulson tcoulson - 26 days ago 6
Javascript Question

Change fill on circle, within an SVG, within an object

So I chose to create an object to put an SVG object into, because I want to replicate it 100 times or more. Here is the SVG:

<svg xmlns="http://www.w3.org/2000/svg" class="ballsvg" viewBox="0 0 98 98">
<g>
<circle class="changeCircle" cx="50%" cy="51%" r="48%" stroke="red" stroke-width="3" fill="blue" />
<text class="changeText" text-anchor="middle" x="50%" y="65%" font-family="Verdana" font-size="30" fill="white" ><tspan>0</tspan> </text>
</g>
</svg>


And my JavaScript that builds out the objects to the div
#svgMain
:

for(var i=0; i<addingTo; i++){
var obj = '<div class="clickBall" data-id="'+String(i+1+totalBalls)+'" ><object class="ball" data="ball.svg"></object></div>'
appendHTMLNodes += obj;
}


Then I found online how to dynamically change the text on that object:

$( "object.ball" ).each(function( index ) {
var textNode = $(this.contentDocument);
textNode = textNode.find(".changeText");
textNode = textNode.children().first();
textNode.text(index+1);
});


Then I wanted to change the fill color when the item is clicked:

$(document).on('click', '.clickBall', function(event) {
var mySVG = $(this).find("object.ball");
mySVG = $(mySVG.contentDocument);
mySVG = mySVG.find(".changeCircle");
console.log(mySVG);
mySVG.attr("fill", "#FF0000");
});


But I cannot figure out how to get the right element, because it never changes the fill, even though I could change the text before.
Thanks in advance for any help.

Answer

You can directly select the .changeCircle and use $(this) property to fill svg. Try this code:

$(".changeCircle").on('click', function() {
    $(this).css({ fill: "#ff0000" });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" class="ballsvg" viewBox="0 0 98 98">
    <g>
        <circle class="changeCircle" cx="50%" cy="51%" r="48%" stroke="red" stroke-width="3" fill="blue" />
        <text class="changeText" text-anchor="middle" x="50%" y="65%" font-family="Verdana" font-size="30" fill="white" ><tspan>0</tspan>  </text>
    </g>
</svg>

UPDATE:

tcoulson wanted to update SVG inside a object tag. Here is how you can access SVG object:

$(function(){ 
    $("#obj").contents().find(".changeCircle").attr({"fill":"lime"}); 
    console.log($("#obj").contents().find(".changeCircle")); 
});