Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attr() fails to set attribute

I am trying to rotate an image via svg's transform. This is the code I have:

<svg width="100" height="100"> 
   <image id="trns" transform="rotate(90,50,50)" width="100" height="100" xlink:href="logo.png"/> 
</svg>

This successfully rotates logo.png by 90 degrees when the page loads. Also, when I change 90 to a different number in firbug's HTML tab the rotation changes accordingly. But when I try to change the value with jQuery, nothing happens:

$('#trns').attr('transform', 'rotate(60, 50,50)');

What does firebug do that my attr line does not?

like image 753
Majid Fouladpour Avatar asked Jul 02 '11 10:07

Majid Fouladpour


People also ask

What is. attr in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to get attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .

Why setAttribute is not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).


2 Answers

Working fine here (with jQuery 1.6.2): http://jsfiddle.net/niklasvh/k3Grd/

Make sure to call it once the DOM is ready:

$(function(){
 $('#trns').attr('transform', 'rotate(60,50,50)');
});
like image 188
Niklas Avatar answered Oct 17 '22 15:10

Niklas


Very strange indeed, this seems to work

$('#trns')[0].setAttribute('transform','rotate(20,50,50)')

Also, if u look at $('#trns').attr('transform'), you are getting an object.. Not enough time to look into that now.

like image 23
Freek Avatar answered Oct 17 '22 13:10

Freek