Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do <script> elements work inside an SVG file, inside an HTML file?

I would like to create an SVG file that, on it's own, has a little animation, controlled by Javascript. Let's assume that I must use Javascript, not the fancy-pants SVG animation tools. That works just fine; a black circle moves around the top left corner of my window:

<svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="400px" height="400px"
    >
  <circle id="c" cx="50px" cy="50px" r="20px" />
  <script>
    var c = document.getElementById('c');
    function f() {
      c.setAttribute('cx', 50 + 30 * Math.random());
      c.setAttribute('cy', 50 + 30 * Math.random());
    }
    setInterval(f, 1000);
  </script>
</svg>

Now, I would like add that SVG to a few web pages. Let's try:

<html>
  <head>
    <title>Test a scripted SVG in an &lt;img&gt; tag
  </head>

  <body>
    <img src="test.svg" />
  </body>
</html>

The result is a black circle that does not move around.

What am I doing wrong? or Where does it say that I cannot do this?

like image 252
Jacob Marble Avatar asked May 22 '14 23:05

Jacob Marble


2 Answers

<script> elements do work in SVG files but not when the SVG file is displayed as an image whether that is via the <img> element or as a CSS background-image. If you want scripts to work then replace the <img> with an <iframe> or <object> element.

Basically, SVG when used in an image context emulates raster images. Raster images aren't scriptable so neither is SVG when it is used in that way.

like image 83
Robert Longson Avatar answered Sep 22 '22 17:09

Robert Longson


I've done this and it worked for me.

But I think there should be the mysterious //<!\[CDATA\[ stuff:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC
  "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  <svg width="200"
       height="200"
       zoomAndPan="disable"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       xml:space="preserve">
    <!-- Script linked from the outside-->
    <script xlink:href="linked_script.js" />
    <script>
      //<![CDATA[
        alert("ble");
      ]]>
    </script>
  </svg>

This is the file I embed it in (and it alerts as expected):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title>Svg embeding test</title>
  </head>
  <body>
    <embed src="test.svg" type="image/svg+xml" /> 
  </body>
</html>
like image 31
Tomáš Zato - Reinstate Monica Avatar answered Sep 22 '22 17:09

Tomáš Zato - Reinstate Monica