Adding JavaScript to SVG
JavaScript in SVG is included in script elements, just as with HTML, except with the addition of CDATA markup surrounding the script. DOM methods are also available for working with the SVG elements.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
<script type="text/ecmascript">
<![CDATA[
window.onload = function() {
const square = document.getElementById('square');
square.onclick = function click() {
const color = this.getAttribute('fill');
if (color === '#ff0000') {
this.setAttribute('fill', '#0000ff');
} else {
this.setAttribute('fill', '#ff0000');
}
};
};
]]>
</script>
<rect id="square" width="400" height="400" fill="#ff0000" x="10" y="10" />
</svg>
<!DOCTYPE html>
<html>
<head>
<title>Accessing Inline SVG</title>
<meta charset="utf-8">
</head>
<body>
<svg width="600" height="600">
<script>
window.onload = function() {
const square = document.getElementById('square');
square.onclick = function click() {
const color = this.getAttribute('fill');
if (color === '#ff0000') {
this.setAttribute('fill', '#0000ff');
} else {
this.setAttribute('fill', '#ff0000');
}
};
};
</script>
<rect id="square" width="400" height="400" fill="#ff0000" x="10" y="10" />
</svg>
</body>
</html>
You can also embed a JavaScript-containing SVG file on the page by using the