Skip to content

SVG and javascript#3

jackdarker edited this page Mar 5, 2023 · 7 revisions

You can also place scriptcode inside the SVG, f.e. to force a color change or hide parts.
This will not work if the svg is embedded as image as the script is supressed for security. Only inlining works!

Add a script-node somewhere in svg. Functions you define here can be called from the svg-elements
<circle ... onclick="foo();"/> (//<!CDATA[[..//]])
<script>//<![CDATA[
function foo(){alert("Alert!");}
//]]></script>

You should encapsulate the script in javascript-comment+xml-CDATA or XML-parser might have issues if there are certain characters in your code.

Inkscape sometimes prepends "svg:" to the nodenames (svg:svgsvg:g...</svg:g>). This also seems to break the script.
Make sure that the followwing attributes are present in the top svg-node. I'm not sure if this solves it?!
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"

Also the script is not accessible from outside by default, we need to expose the functions: Below is a page with a button and SVG with 2 rects. The second rect uses onmouseover to modify style. But we need more direct control.
The button should somehow call makeGreen inside the SVG to change color of one of those rects.
To make makeGreen accessible, we attach it to the svg itself. This is done in the SVG script which is called once at pageload ("this" is "window" not the svg!).
(Note that the svg-script is encapsulated in CDATA, but that might not be necessary.)
Then, in html-JS we can use DOM to get a ref to the SVG which now provides makeGreen.

<html> ... <body>
<button type="button" onclick="foo();">green</button>
<svg id="svg5"><defs>...</defs>
<g id="layer1" ...>
<rect id="rect1058".../>
<rect id="rect1250" onmouseover="this.style.fill=&quot;red&quot;;".../>
</g>
<script>//<![CDATA[
function makeGreen(){ const el= document.getElementById("rect1058"); el.style.fill="green";}
const ctrl = document.getElementById("svg5");
ctrl.makeGreen=makeGreen;
//]]></script>
</svg>
//somewhere in your html-page:
<script>function foo(){ const _svg=document.getElementById("svg5");_svg.makeGreen();} //or _svg=document.documentElement ?!
</script>
</body></html>

Add this function to toggle visibility of ome element (per ID):
function toggleVisible(id){const elmt = document.getElementById(id);
var x=window.getComputedStyle(elmt).getPropertyValue('visibility');
elmt.style.visibility=(x==='hidden')?"visible":"hidden";}
or for multiple elements sharing the same data-label attribute
function toggleVisible2(label){const elmt = document.querySelectorAll('[data-label='+label+']);
var x=window.getComputedStyle(elmt[0]).getPropertyValue('visibility');
var visib=(x==='hidden')?'visible':'hidden';
elmt.forEach((x)=>x.style.visibility=visib);}

Clone this wiki locally