Reputation: 477
I have an inline SVG like
<svg>
<g id="1" transform="<list of transformations>">
<path d="">
<circle cx="" ...>
</g>
...
</svg>
with many groups and I want to move them with JavaScript/jQuery. I take values (like rotation) from inputs on the site and tried to use
$("#1").attr("transform", "<list of new transformations>");
but it doesn't work. When it is executed from the JS file you can't see any change. When I insert it manually in the console I can retrieve the value with $("#1").attr("transform")
, but it doesn't lead to a visible change and doesn't change the elements in the inspector. Tested in Firefox/Chrome.
How can I change the svg with javascript or jQuery at runtime?
Edit: The problem was, that all the id's occured in another part of the script, so the wrong one's got selected.
Upvotes: 1
Views: 593
Reputation: 12448
Overall, your approach seems correct. However, the code below demonstrates how this can be done, so maybe that will show you some subtle mistake you are making.
You can use jQuery or vanilla JavaScript to modify SVG elements as shown in the code below, i.e. using .attr(attributeName, attributeValue)
with jQuery, or .setAttribute(attributeName, attributeValue)
for vanilla JavaScript.
To change the transforms, you have to follow the appropriate syntax (e.g. discussed here).
$('#b2').attr('fill', 'red');
document.querySelector('#c2').setAttribute('fill', 'magenta');
$('#b2').attr('transform', 'translate(0, 20)');
document.querySelector('#c2').setAttribute('transform', 'rotate(10, 250, 80)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Top row: three identical yellow rectangles.</p>
<p>Bottom row: three similar rectangles. The second is modified using jQuery, the third using vanilla JavaScript</p>
<svg>
<rect id="a1" x="50" y="20" width="40" height="20" fill="yellow" />
<rect id="b1" x="150" y="20" width="40" height="20" fill="yellow" />
<rect id="c1" x="250" y="20" width="40" height="20" fill="yellow" />
<rect id="a2" x="50" y="70" width="40" height="20" fill="yellow" />
<rect id="b2" x="150" y="70" width="40" height="20" fill="yellow" />
<rect id="c2" x="250" y="70" width="40" height="20" fill="yellow" />
</svg>
Upvotes: 1