I know how to move a div element using top/left position increments. But I heard that translate3d gives performance improvements, and so I wanted to check it out.
Lets say I have this,
var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.background = 'red';
div.style.position = 'absolute';
document.body.appendChild(div);
The following,
div.getBoundingClientRect().left
gives the value 8.
Now, calling
div.style.transform = 'translate3d(10px,0,0)'
moves the element to the right by 10px as expected as seen by
div.getBoundingClientRect().left
giving the value 18.
But repeatedly executing,
div.style.transform = 'translate3d(10px, 0, 0)';
does not move the div to the right repeatedly. Instead I have to increment the first argument of translate3d
to higher values (eg. 20, 30 etc) to move it repeatedly.
This makes me think the translation is calculated from some initial point. But googling around, I could not find how to update this initial point, so that translate3d(10px, 0, 0)
works in a loop.
I tried updating the div.style.left
property, but it still does not work.
So can someone tell me how translate3d
calculates the translation? And if there is a way to use translate3d(10px,0,0)
and some origin resetting, to make a div move repeatedly?
(The end goal is to make a div move to the right every time it is clicked, using translate3d
)