0

I'm using SVG in my project and want to toggleClass with jQuery on the textpath elements when clicked.

So I was thinking about:

$("text#names > textpath").click(function() {
    $(this).toggleClass("newClass");
});

on HTML source:

<text id="names" class="clickthrough">
    <textpath class="zoom1" href="#text1" font-size="12.1"></textpath>
    <textpath ... </textpath>
</text>

but nothing happens. If I do $("text#names") I get the class clickthrough. So it is working, just the textpath is maybe not known to jQuery. So I found http://keith-wood.name/svgref.html but before using this, I would like to be sure if it is really needed for my case.

kwoxer
  • 3,734
  • 4
  • 40
  • 70

1 Answers1

1

jQuery's .class doesn't work with SVG elements, you'll have to use attr instead:

$("text#names > textpath").click(function() {
  $(this).attr("class", function(_, val){
    return (val.indexOf("newClass")+1) ? val.replace(" newClass","") : val+" newClass";
  });
});

Check out the jsFiddle demo.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • I mean I not even get a result when I have alert("test"); So the main issue is on the click thing. – kwoxer Feb 02 '15 at 17:08
  • @kwoxer Oh, that's odd - mind posting your testing code? – theonlygusti Feb 02 '15 at 17:15
  • Sure =) http://jsfiddle.net/kwoxer/5uc17jwr/15/ if you remove > textpath it works. No real clue about this. =/ – kwoxer Feb 02 '15 at 17:23
  • @kwoxer been studying it for a while, and I'm baffled; I think it has to be something with the order the elements are being added, because in my example it works fine. – theonlygusti Feb 02 '15 at 17:45
  • But how different should I order it. I mean I create some defs and use them afterwards with the fill attribute. – kwoxer Feb 02 '15 at 18:00
  • Okay I think this issue here can be workarounded. Do you know a way to set the click event on all elements that have a class beginning with let's say "event_..."? Nvm: found already http://stackoverflow.com/questions/10708796/jquery-hasclass-can-it-be-given-the-beginning-of-class-name-to-get-the-full-cl – kwoxer Feb 02 '15 at 18:22
  • Got it working now. The tricky thing was that I have some other elements with the same class. And now hovering a class shall look for similar names class on the SVG. Works now with your code. Big thanks again. – kwoxer Feb 02 '15 at 20:43
  • So, in the end, did you have to use my `.attr` method? Or did it work with `.class`? – theonlygusti Feb 03 '15 at 17:11
  • Hey, yeah indeed it just seem to work with .attr. I was not able to get it working with .class. – kwoxer Feb 03 '15 at 17:57