Passing information back and forth between SVG and HTML

While some good books on SVG have begun to appear proportionally little space seems to have been devoted to the interaction between HTML and SVG through JavaScript.

However, there are plenty of good reasons for wanting to do this:

  1. Constructing vector graphics on the fly is something that HTML with JavaScript is not well suited to do, though it is perfectly natural in SVG.
  2. Managing the user-interface through textareas, select objects, and all the interactive devices that JavaScript inherits from the HTML DOM is not something that comes native to SVG. Building code to manage keystrokes and textwrap within SVG would be painstaking for those SVG documents which have as their final destination, the web.
  3. SVG does not need HTML (pure SVG web sites have been created demonstrated how versatile SVG is). However, the web is predominantly HTML, and this is not likely to change in the next few years. Exploring ways of interacting between the two DOM’s is natural.


A. Embedding SVG in HTML documents

Placing an SVG object into a web page is typically done with an <embed> tag.

<html><body>Example of embedding SVG into an HTML document<br> <embed src=”example.svg” height=200 width=200></body></html>
Although, we may also use <object> or <iframe> tags to include SVG content into an HTML document, neither seems (based on natural experiments) to allow for the subsequent traversal of the SVG DOM by JavaScript within the HTML. It is possible, over time, that the <object> may become a preferrable approach since it enjoys greater standards support from the WWW Consortium. Though as of this writing, there appears to be no way of interrogating the contents of an <object> tag.
Frequently, we may wish to have the size of the SVG object adjusted to fit the size of the browser window. The following script determines how to measure the available screen real estate and then resizes the embed to fit from the bottom of an div tag to the bottom of the screen:
<html><head><script> window.onload=prepare function prepare(){ if (document.body.clientWidth){ rightedge=document.body.clientWidth bottomedge=document.body.clientHeight Qhi=document.getElementById("Q").clientHeight }else{ rightedge=window.innerWidth bottomedge=window.innerHeight Qhi=document.getElementById("Q").innerHeight } document.getElementById("S").setAttribute("width",rightedge) document.getElementById("S").setAttribute("height",bottomedge - Qhi - 20) document.getElementById("S").style.left=0 document.getElementById("S").style.top=Qhi+10 } </script></head> <BODY><div id="Q" style="position:absolute;top:0"> <p>Here is an ordinary web page with an SVG embed that is resized and repositioned</p> <hr></div> <embed id="S" src="clickovals.svg" style="position:absolute; left:200;top:0"> </body></html>