Home » Jquery » svg – jquery attr works but animate fails-Exceptionshub

svg – jquery attr works but animate fails-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have an svg line with id=’slope’. I want to change the slope by altering the y1 and y2 values. This works fine:

$('#slope').attr({y1:10});
$('#slope').attr({y2:30});

As expected, the line changes angle so it starts from y=10 and ends at y=30. However, I cannot animate it. This gives me an error claiming that y1 and y2 are read-only attributes:

$('#slope').animate({y1:10});
$('#slope').animate({y2:30});

Is this a bug in jquery or is jquery unable to animate y1 and y2 of a line. I tested this with the cx and cy attributes for circles and it works fine. So, I know that jquery can animate position of svg elements. For some reason, it cannot do lines from what I am seeing.

I am using jquery 3.4.1, in case this is a bug.

How to&Answer:

The description of JQuery’s animate is:

Description: Perform a custom animation of a set of CSS properties.

Whereas the x and y attributes of an SVG line are exactly that, attributes.

A future specification may convert the ‘x1’, ‘y1’, ‘x2’, and ‘y2’ attributes to geometric properties. Currently, they can only be specified via element attributes, and not CSS.

They are not CSS properties and therefore jQuery won’t animate them. If you want to animate lines you’ll need to use SMIL or javascript (or a library that internally uses SMIL or javascript).

Somewhat confusingly the SVG 2 specification has made circle’s cx and cy mapped CSS properties rather than attributes. In SVG 1.1 they too used to be attributes.