Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG <script> element: inside or outside?

I see <script> tag can be used within svg tag (ref). Also, the elements within svg tag is accessible through JavaScript outside the tag as they are part of DOM. I could not find much details on which is better. Normally, I keep all the JS code in separate file and include the reference in html. Can I do the same with script targeted to svg elements as well. Also, I read I can also give a link to an external JS file inside the svg tag.

To be more clear, Say I have a webpage (html5) with embedded svg tag in it. the svg contained few basic shapes, which I need mouse interaction. I may use jQuery, but not other external plugin. Would u recommend keeping all the JavaScript (for elements outside and inside svg) in one single file, or keep the svg part separate. Also is it ok to refer to the elements within the svg tag using jQuery? Any inefficiency if I do it?

like image 944
bsr Avatar asked May 02 '11 21:05

bsr


2 Answers

Placing a <script> element inside SVG (whether you use code inline or referenced in another file via xlink:href) is correct when your script is appropriate for the SVG itself, with or without another context it may be placed within. This is necessary, for example, if you have just a scripted SVG document.

For example, let's say you have an HTML page and you include two SVG files.

  • The first SVG file has some custom animation created through JavaScript. This SVG file should have its own script element directly.

  • The second SVG file is just a fancy image, and you want to make it so when you click on that image a form on your HTML page is submitted. For this, the script should be in your HTML page, since it talks to both the SVG and your HTML form. Here's a similar example, where buttons in the HTML are used to control the SVG.

The line becomes fuzzier when you are inlining your SVG content in something XHTML5, instead of referencing an external SVG file. Is that SVG content its own beast, or is it just as much a part of the HTML page as a particular paragraph of text?

I personally tend to inline my SVG into the HTML and thus keep all my script outside the SVG. Either will work, though.

like image 66
Phrogz Avatar answered Nov 10 '22 04:11

Phrogz


You can call an external file using the xlink:href attribute.

<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
     <script type="text/ecmascript" xlink:href="script.es"/>
</svg>

(source: W3C)

Also, I recommend you RaphaelJS, a JavaScript library allowing cross-browser vector drawing.

like image 29
Mathieu Rodic Avatar answered Nov 10 '22 05:11

Mathieu Rodic