Andrew Hassan
Andrew Hassan

Reputation: 591

How do I update an SVG text element using Snap.svg?

I'm using Snap.svg to load an SVG image and add text elements to it. However, I need to be able to update the text elements as the page loads.

Right now, I'm doing something like this:

var svg = Snap("#selector");
var text;
Snap.load(path_to_file, function(f) {
    svg.append(f);
    var g = svg.select("g");
    text = g.text(x_pos, y_pos, label);
}

Let's say I want to update the text later, how do I do this? I am guaranteed to update the text object after it's been created after calling load.

The only way I've managed to modify the text is by setting an id to the element and then doing it with jQuery like this:

self.selector.find("#my_id")[0].textContent = "New text";

However, this feels really wrong and I think I might just be missing something with the Snap API.

Upvotes: 14

Views: 11480

Answers (3)

malcomwu
malcomwu

Reputation: 167

Another way, you can directly get a reference of DOM node using Element.node, so you can mess around

text.node.textContent = "New text";
text.node.innerHTML = "New text";
text.node.innerHTML = 'a<tspan dy="5">2</tspan>'

Upvotes: 4

Lukasz Frankowski
Lukasz Frankowski

Reputation: 3175

With jquery

$(s.select('#id').node).text('new text');

Upvotes: 0

Ian
Ian

Reputation: 13842

I think it should be as simple as

text.attr({ text: 'my new text'});

so

setTimeout( function() { text.attr({ text: 'my new text'}) }, 2000 );

would test it

Upvotes: 27

Related Questions