Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMl+SVG+JavaScript: change text at runtime?

I am about to migrate a few Flash-based applications to HTML+JavaScript+SVG (the single target rendering engine is Webkit).

I'm completely new to SVG and I'd like to know if I can use a SVG as a template image to fill the screen and change contained text on the fly from the JavaScript code embedded in the HTML page.

What I want to do is: draw the basic structure of the page in Inkscape (with some graphics and text placeholders) and then just display the SVG in the HTML page and fill the text placeholders via JavaScript.

I could get the same result by displaying a static SVG image in the background and place some absolutely positioned DIVs on top of it to display the text, but I'd like to design the position, size and style of the text labels from within Inkscape.

Can this be done? How?

I'm using the Prototype framework, not JQuery.

like image 752
Udo G Avatar asked May 30 '11 09:05

Udo G


2 Answers

Try jQuery. Set manually an ID to an SVG-TextNode, and then try:

$("#my_id").textContent = "new Value";

May be it works. Otherwise try:

document.getElementById("my_id").textContent = "new Value";
like image 139
Christian Kuetbach Avatar answered Oct 18 '22 11:10

Christian Kuetbach


How you access the SVG depends on exactly how you include it in your page. You can either use and object or embed element and link to the SVG, or include it inline in the page. Note that including it via an img element won't work - the SVG will be treated as an image 'black box', you won't be able to access the internal structure.

Embedding via an object is straightforward and will work in all browsers which support SVG:

<object id="svg_object" width="672" height="243" data="myimage.svg" type="image/svg+xml">
    No SVG support
</object>

Then to get at the internal structure you need to get the contentDocument:

var svg = $('svg_object').contentDocument;
var svgel = svg.getElementById('myid');

Note that the internal DOM of the SVG won't be automatically extended by prototype.js in this case, so you'll have to fall back on regular DOM methods.

Embedding the SVG directly in the page will work if you serve your page as application/xhtml+xml or if the browser has an HTML5 compliant parser (Firefox 4, Chrome, IE9 but not Opera or earlier Firefox). However, now your prototype.js methods will work directly with the SVG elements, making certain things much more simple:

var svgel = $('myid');

I've done a couple of examples: object, inline. They work for me in Firefox 4, you may need to do some messing around to get them working in other browsers (with the caveats mentioned above as far as support is concerned).

like image 41
robertc Avatar answered Oct 18 '22 09:10

robertc