Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change parent of an element with transform translate animation?

enter image description here

I want to move an element from one parent to another parent. Here I wanna apply CSS transform animation.

function abc() {
let child = document.querySelector("#child");
let parent = document.querySelector("#div_b");

parent.appendChild(child);
}
<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 onclick="abc()">move</button>
like image 992
turnamong1452 Avatar asked Sep 02 '25 03:09

turnamong1452


1 Answers

You can find out where the element is currently, move it to its new parent and find out where it is now, put it back in its original parent and set an animation for it to translate to its new position.

When the animation has completed then you put the element into its new position (ie into its new parent).

function abc() {
  const child = document.querySelector("#child");
  const parent = document.querySelector("#div_b");
  const parentOriginal = document.querySelector("#div_a");
  parentOriginal.appendChild(child); //put back to where it was
  const x0 = child.getBoundingClientRect().left;
  const y0 = child.getBoundingClientRect().top;

  parent.appendChild(child);
  const x1 = child.getBoundingClientRect().left;
  const y1 = child.getBoundingClientRect().top;
  parentOriginal.appendChild(child);
  child.style.setProperty('--dx', (x1 - x0) + 'px');
  child.style.setProperty('--dy', (y1 - y0) + 'px');
  child.addEventListener('animationend', function() {
    parent.appendChild(child);
    child.classList.remove('move');
  });
  child.classList.add('move');
}
.move {
  animation: move 2s linear 1;
}

@keyframes move {
  0% {
    transform: translateX(0) translateY(0);
  }
  100% {
    transform: translateX(var(--dx)) translateY(var(--dy));
  }
}
<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 onclick="abc()">move</button>
like image 59
A Haworth Avatar answered Sep 04 '25 18:09

A Haworth