I'm trying to move a group of circles when a user clicks one of them. The group only moves once on the first click, but not afterwards. Here's the sample code I'm using,
function move_circle(e)
{
var grp = e.target.parentNode;
grp.setAttribute("transform", "translate(" + 50 + ", " + 50 + ")");
}
<g onclick="move_circle(evt)">
<circle cx="150" cy="100" r="25" fill="red" />
<circle cx="170" cy="120" r="5" fill="red" />
</g>
Every time that you click a circle, the event handler is setting the
transform
attribute of theg
element to"translate(50, 50)"
. I believe what you intended to do is to repeat the translation every time a circle was clicked. In other words, you want to compose the translation with the one that is already applied to the element. Like so:If no transformation has been applied, it will apply the translation as you were previously doing. If a transformation's already being applied to the element, then you use the existing transformation matrix, apply another translation to it, and then set the result of that to the transformation matrix of the element. (The
translate()
operation does not mutate the matrix. It returns a copy of the matrix with the operation applied to it. Thus, you have to update the transformation with that new matrix.)