Is there a way to animate an element from one grid cell to another

Viewed 382

I would like to have an element slide over to another grid cell. I had assumed it would be easy using jQuery's .animate() method, but you cannot change the grid CSS through there. You also cannot use the .css() method, because then it just snaps into place and it does not slide into place.

Is there an easy way to do this with CSS and javascript/jQuery? Is there another API I could be using to make this easier? I honestly don't know where to start.

1 Answers

The only way I can think of to sort of do this is to almost fake it? Get the current x/y coordinates of the box, put it into it's new position, get the new x/y coordinates, snap it back, animate it using position: relative, and then once the animation is done, take off the relative positioning and update it back to the right coordinates.

Something like this:

const b = document.getElementById('b');
document.getElementById('demo').addEventListener('click', function() {
    const { top: top1, left: left1 } = b.getBoundingClientRect();
    b.style.transition = '2s';
    b.style['grid-row-start'] = 3;
    b.style['grid-row-end'] = 4;
    const { top: top2, left: left2 } = b.getBoundingClientRect();
    b.style['grid-row-start'] = 2;
    b.style['grid-row-end'] = 3;
    setTimeout(() => {
        b.style.transition = 'auto';
        b.style['grid-row-start'] = 3;
        b.style['grid-row-end'] = 4;
        b.style.top = 0;
        b.style.left = 0;
    }, 2000);
    
    b.style.left = (left2 - left1) + 'px';
    b.style.top = (top2 - top1) + 'px';
});
body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
}

.box {
  top: 0;
  left: 0;
  transition: 2s;
  position: relative;
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
}
.b {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 2;
  grid-row-end: 3;
}
.c {
  grid-column-start: 3;
  grid-column-end: 4;
  grid-row-start: 2;
  grid-row-end: 3;
}
.d {
  grid-column-start: 1;
  grid-column-end: 2;
  grid-row-start: 1;
  grid-row-end: 2;
}
.e {
  grid-column-start: 1;
  grid-column-end: 2;
  grid-row-start: 2;
  grid-row-end: 3;
}
.f {
  grid-column-start: 3;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 2;
}
<button id="demo">Click Me</button>
<div class="wrapper">
  <div class="box a">A</div>
  <div id="b" class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>

Related