0

I'm using the library SVG.js and svg.select.js to manipulate svg objects, I have problems selecting text elements as you can see in this example. With the ellipse there are no problems while this is the error message when trying to select the text: "Uncaught TypeError: this.parent.group is not a function" This is my code:

var draw = SVG('drawing')
var selectedelement;
var g = draw.group();
text = g.text('Perepepeeeee');
var myEllipse = g.ellipse(50, 50);
myEllipse.move(200, 0);

g.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement=SVG.get(event.target.id).selectize({ deepSelect: true })
});

Where am I wrong?

3
  • You use event.target.id. Does your group has an id? Because you never set one. Beside that you would select the group and not the text inside. Commented Jun 13, 2018 at 16:36
  • Ok the problem was that the element corresponding to the event.target.id was the tspan inside the text so parent().group() in svg.select.js gave the error. [In this way it seems to work: selectedelement=SVG.get(event.target.id).parent().selectize()]. Thanks for your help :) Commented Jun 13, 2018 at 19:07
  • There is actually no need to SVG.get the element in the handler. Because the this context in the handler is bound to the group. No need to get fancy Commented Jun 13, 2018 at 19:36

1 Answer 1

2

You access the event.target.id in your event handler. The target property always points to the node the event was invoked on. In your case thats the tspan. However, what you want is the text.

svg.js calls the handler in the context of the element it was bound on. So you can simply use this to get the group and search the text-element from there:

g.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement = this.select('text').first().selectize({ deepSelect: true })
});

However, the best way would be to bind the click event to the text at the first place so you dont need to traverse through the dom

text.on("click", function (event) {
   if (selectedelement!=null)
      selectedelement.selectize(false, { deepSelect: true });
   selectedelement = this.selectize({ deepSelect: true })
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes true! I had adopted this solution because within the group I could have other elements that I still want to select (eg the ellipse)... but I think you're right that it's not particularly elegant :/
When you find this answer appropriate you might want to select it as answer so people can see, that this question was answered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.