In addition to A Haworth's excellent answer, you could further iterate on this by using the Web Animations API. This API uses the same fundamentals as CSS Animations, but allows you to perform the actions through JavaScript.
Like Haworth, get the first position of the #child
element. Then move it to it's destination. Measure the position of the #child
again. Subtract the last position from the first position. The result of this subtraction is the difference between the two points, otherwise known as the delta.
Use the delta to translate the #child
to it's previous first and then animate it to the last known position.
const moveButton = document.querySelector('#move');
const origin = document.querySelector('#div_a');
const target = document.querySelector('#div_b');
const child = document.querySelector("#child");
moveButton.addEventListener('click', () => {
const { left: x0, top: y0 } = child.getBoundingClientRect();
target.append(child);
const { left: x1, top: y1 } = child.getBoundingClientRect();
const dx = x0 - x1;
const dy = y0 - y1;
if (dx === 0 && dy === 0) {
return;
}
const transformFrom = `translate3d(${dx}px, ${dy}px, 0)`;
const transformTo = `translate3d(0, 0, 0)`;
const animation = child.animate([
{ transform: transformFrom },
{ transform: transformTo },
], {
duration: 2000,
easing: 'linear',
});
});
<div id="div_a" style="height:30px; width:30px; background-color:yellow;">
<div id="child" class="new-box">
<div style="width: 20px; height: 20px; background-color: green;"></div>
</div>
</div>
<div id="div_b" style="height:30px; width:30px; background-color:red;">
</div>
<button id="move">move</button>