1

I've been making some SVG append to my code using jQuery and I have a problem with my animation on svg element. The thing is that when I insert this code

<circle fill="#2380c2" cx="20.5" cy="12.5" r="1.5" id="circ1">
<animate begin="svg_1.mouseover" end="svg_1.mouseout" from="20.5" to="20.5" dur="1.5s" repeatCount="indefinite" attributeName="cx" values="20.5;18.5;20.5;22.5;20.5"></animate
</circle>

using append(), attributeName is converted to attributename and my Google Chrome doesn't recognize it as a valid attribute.

Any help on how to solve this append() issue?

bigcat
  • 152
  • 2
  • 11
  • 1
    Probably duplicate of: http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element/3642265#3642265 – Paul LeBeau Feb 20 '14 at 23:33

1 Answers1

0

First of all, jQuery isn't able to append elements from the SVG namespace by default. Try creating the element with document.createElementNS(). Second, jQuery's attr calls toLower on attribute names, so it wont work for camelCased attributes like SVG uses (see this jQuery bug). You can use a different library that does support SVG, like D3, or use the native javascript method setAttribute. For example:

svgEl = $(document.createElementNS('http://www.w3.org/2000/svg', 'circle'));
svgEl.attr({fill: '#2380c2', cx:'20', cy:'20', r:'10'}).appendTo('#theSvg');

animateEl = $(document.createElementNS('http://www.w3.org/2000/svg', 'animate'));
animateEl.attr({from:"10", to:"20", dur:"3s"}).appendTo('circle');
$animateEl = $("animate")[0];
$animateEl.setAttribute("attributeName", "r");
$animateEl.setAttribute("repeatCount", "indefinite"); 

Demo: http://jsfiddle.net/CodyRank/7L6wX/1/

Cody
  • 2,467
  • 2
  • 21
  • 30
  • I did that already. I have a function for creating SVG: [code]function svg(element,eldict,divid) { $el = $(document.implementation.createDocument(null, null, null).createElementNS('http://www.w3.org/2000/svg', element)); $(divid).append($el.attr(eldict)); }[/code] but when I append attribudets they are lowercase and the animation dosen't work – bigcat Feb 21 '14 at 10:36
  • And what are you passing to that function? It's difficult to help with incomplete code. Could you post a full example on http://jsfiddle.net/ ? – Cody Feb 21 '14 at 17:12
  • Ahh, it looks like `attr` in jquery calls toLower. You'll have to use the built in setAttribute instead. I'll update my answer, but here's a sample: http://jsfiddle.net/CodyRank/7L6wX/ – Cody Feb 21 '14 at 17:54
  • Yes I got it. I used pure JS instead of jQuery and setAttribute did the job. – bigcat Feb 25 '14 at 15:36