svg and html

Using an uptodate browser (or a java script library, such as svgweb) it is fairly easy to integrate a svg file into a html page and to handle the svg-file from html, for a primer, see e.g. alistapart.com. Basically, when you have the svg in your page, you use

svgobject.contentDocument.getElementById( ... );

where svgobjectg is the <object> that embeds the svg, contentDocument takes you to the svg-file itself, and using getElementById or other dom-functions, you can access all elements of the svg, manipulating them to your heart’s desire. I am using it in an own application for adding live data to a stripchart.

However, it was not so easy to find out how to go the other way. In the stripchart application above, I have set an onclick-handler within the svg. It draws a horizontal line where the click was, then a timed updater in the html inspects the svg, finds that the line is visible,

if (svgobject.contentDocument.getElementById('markerline').stroke=="black"){
doSomething();
}

and does an action (in my case, reads out the value of the stripchart at the location of the line).

All fine and dandy, as long as you do not mind waiting till the updater fires.

As long as we have access to all parts of the svg from javascript in the html-document, the obious way of fixing this should be to put an eventhandler “into” the svg from the html’s javascript – eg

svgobject.contentDocument..getElementById('area').addEventListener('click',function(event){alert('change');});

This works! – but only in the Google chrome browser.

Doing a lot of head scratching and googling, at last I found a page on svg scripting in the MDC doc centre. It turned out that I have the object parent for my use that points ‘out’ from the svg. So if I put a

<rect x="-30" y="0" width="260" height="400" stroke-width="2" fill="lightgray" onclick="parent.test()" />

into my svg, it calls the test() function in the html’s javascript.

Tested in Firefox 3.6.13, opera 11.01, chrome 9.0.597.98 and Internet Explorer 8.0.6001 – the latter armed with svgweb 2011-02-03 “Lurker Above”.

No more time for blogging now, off to do some real work!

This entry was posted in Diverse, html, svg. Bookmark the permalink.

One Response to svg and html

  1. Pingback: Making stripcharts using svg and javascript | Mortens meninger

Comments are closed.