barrylachapelle
barrylachapelle

Reputation: 987

Find the fill of a child SVG node with Jquery?

I have an svg with 5 children > 1 circle and 4 paths. Each has a a different fill color. Is it possible to understand which child has been clicked and return the fill?

Something like...

$("#svgname").click( function(){
    alert($(clickedchildname).attr("fill"));
 });

Thank you.

UPDATE:

My code is set up like this...

HTML

<div class="">
    <img src="img/colorsystem/darkblue.svg" height="170" width="170" id="darkblue">
</div>

JS

$("#darkblue").children('g').children().click(function(){
  alert($(this).attr("fill"));
});

SVG

<?xml version="1.0" encoding="utf-8"?>
<svg>
<g id="darkblueholder">
    <circle id="base" class="st0" cx="85.1" cy="84.3" r="71.4"/>

Upvotes: 0

Views: 594

Answers (1)

Pavel Gatnar
Pavel Gatnar

Reputation: 4053

Yes, it is possible using children method, when the svg is inline:

$("#svgname").children().click(function(){
  alert($(this).attr("fill"));
});

or referenced by use:

<svg height="170" width="170">
   <use id="svgname" xlink:href="img/colorsystem/darkblue.svg#darkblueholder"></use>
</svg>

$($("#svgname").attr("instanceRoot")).children().click(function(){
  alert($(this).attr("fill"));
}); 

You can even specify child type using .children('path, circle').

It is not possible to access svg tree loaded using img.

Upvotes: 2

Related Questions