Skip to content

SVG and javascript#3

jackdarker edited this page Dec 14, 2022 · 7 revisions

If you inline SVG in HTML, you can also place scriptcode inside the SVG.
But how to trigger it as we cant call it directly?
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.
(Note that the svg-script is encapsulated in CDATA, but that might not be necessary.)
Then 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>

<script>function foo(){ const _svg=document.getElementById("svg5");_svg.makeGreen();}
</script>
</body></html>

Clone this wiki locally