Color area in SVG xlink imported file using JavaScript

84 Views Asked by At

I have following index.html file:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$( document ).ready(function() {
    $("#inline").click(function (event) { $(event.target).attr('style', "fill: yellow"); })
    $("#abc").click(function (event) { $(event.target).attr('style', "fill: yellow"); })
    $("#def").click(function (event) { $(event.target).attr('style', "fill: yellow"); })
    $("#circle2").click(function (event) { $(event.target).attr('style', "fill: yellow"); })
});
</script>
</head>
<body>

<svg id="inline" height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="25" stroke="black" stroke-width="3" fill="blue" />
</svg>

<svg id="abc" height="100" width="100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <image id="def" x="0" y="0" height="500" width="500" xlink:href="red.svg" />
</svg>

</body>
</html>

and file red.svg:

<svg id="circle2" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="25" stroke="black" stroke-width="3" fill="red" />
</svg>

In browser I see at index.html file 2 circles. Blue and red. It is ok.

I want to change color of circle after I click on it. At "inline" blue circle it works. But in inserted svg (red) nothing happens.

How can I color imported image?

Or is there any other working way how to import svg file? I cannot uset jQuery.load() because I need import files from file:// url.

1

There are 1 best solutions below

0
On

CSS styles do not work across doument boundaries. You can set a style property on #def, but it is not inherited by the contents of red.svg.

You either need to:

(a) inline red.svg, or

(b) embed it via which let's you access its contents via the DOM (via my_object.contentDocument)