Skip to content

Instantly share code, notes, and snippets.

@nasitra
Created May 23, 2016 10:30
Show Gist options
  • Save nasitra/e491438ec87c97daca7e149a0d233165 to your computer and use it in GitHub Desktop.
Save nasitra/e491438ec87c97daca7e149a0d233165 to your computer and use it in GitHub Desktop.
Access JavaScript function in SVG
Display the source blob
Display the rendered blob
Raw
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
<script><![CDATA[
document.fillRandomColor = function() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
document.querySelector('rect').setAttribute('fill', 'rgb(' + r + ', ' + g + ', ' + b + ')');
};
]]></script>
<rect x="10" y="10" width="200" height="100" stroke="black" fill="white" />
</svg>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<object data="image.svg" type="image/svg+xml" style="pointer-events: none;">
</div>
<script>
document.getElementById('container').onclick = function() {
var object = document.querySelector('object');
object.contentDocument.fillRandomColor();
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment