I have an HTML file named index.html, in which I have included a svg (using the object-tag) and a js-file (using the script-tag). The js functions all work perfectly when called inside the HTML file. Now, when I want to access one of my js functions inside the svg-file, I have to link to the js-file in my svg file (using xlink). The functions still work inside the svg file, but as soon as these functions refer to any element in the HTML file (e.g document.getElementById('div1')), they don't work anymore (My guess: Probably because the function doesnt look for the element inside the HTML, but inside the SVG-file.) What can I do to make these functions work again?
3 Answers
You can use the top or parent objects to get from the svg to the container html. There is a complete svg to container html and container html to svg example with extensive comments here.
Comments
When you embed a JS function in an SVG, they are always executed in the private scope of the SVG, and thus can not access anything outside of it.
When you want to create an interactive web application with dynamic SVGs, you should put the JS functions which modify the SVG in the javascript code of the HTML. You can access an SVGs document tree from HTML-embedded javascript by getting the .contentDocument of the <object> element.
1 Comment
window.parent.document called from the svg document gives you the parent html document.In modern browsers, you can simply place the svg directly within the HTML, and JS (and CSS) will work seamlessly on both.
<div>
<svg:svg xmlns:svg="www.w3.org/2000/svg" version="1.1" height="100" width="100" viewBox="0 0 100 100">
<svg:circle id="circle" cx="50" x="50" y="50"/>
</svg:svg>
</div>
<script>
document.getElementById("circle").style.fill="red";
</script>