2

I want to create an interactive SVG HTML-Page. For example: If I click on a rectangle, I want to display a new SVG-Image.

Because my SVG-Files are separate, I want to include them via the HTML-Object Tag.

I've browsed the web for a while, but I just fail to adress single elements of my SVG-File to change their attributes or add functions etc.

My HTML-File:

<!DOCTYPE html>
<html>
<body>  
<object data="svg-test.svg" type="image/svg+xml" id="svg" width="100%" height="100%"></object>

    <script>
    window.onload=function() {
    // Get the Object by ID
    var svgObject = document.getElementById("svg");
    // Get the SVG document inside the Object tag
    var svgDoc = svgObject.contentDocument;
    // Get one of the SVG items by ID;
    var svgItem = svgDoc.getElementById("svgID");
    // Set the colour to something else
    svgItem.setAttribute("fill", "lime");
    };
    </script>


</body>
</html>

The SVG-File:

<svg width="900" height="600"  xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">

    <rect x="100" y="120" width="200" height="350"      
    style="fill:white;stroke:black;stroke-width:2;fill-opacity:1.0;stroke-opacity:1.0"  
    id="svgID"/>

 </svg>

Instead of using contentDocument I also tried getSVGDocument() but this also did not work.

SimpleFlow
  • 31
  • 3
  • In my case, contentDocument wasn't working (or at least not in some browsers) because I hadn't yet waited for (not just window) to load. See: http://stackoverflow.com/a/15680844/5285945 (where a comment of mine also links to another relevant answer). – Max Starkenburg May 17 '16 at 22:04
  • Thank you for your comment. I also tried `` but it did not work. – SimpleFlow May 18 '16 at 06:00
  • In the first thing you tried, it would need to be `svgDoc = a.contentDocument` instead of just `svgDoc = contentDocument` (or maybe that was just a transcription error?) – Max Starkenburg May 18 '16 at 11:35
  • Sorry, this was a transcription error. The problem was using Chrome with local files. But thank your for your answer! – SimpleFlow May 18 '16 at 14:13

1 Answers1

0

It seems that Chrome has problems loading objects when no (local) server is set up.

I tried Microsoft Edge /IE and the problem was solved. I could access all elements within the SVG file.

SimpleFlow
  • 31
  • 3
  • 1
    I think If you are using Chrome. Because Chrome don't allow xmlhttprequest to request local file. So it can not load your file you can add --allow-file-access-from-files to the start target command of chrome shortcut. This can allow xmlhttprequest to load local resource – NuttLoose May 18 '16 at 08:21