1

I'm trying to make animation for moving block to the right and to the left. But I can't understand why it's not working. For example, it works well for on click event. Here is my codepen. Thanks

const box = document.getElementsByClassName('box')[0];

document.addEventListener('keydown', function({
  keyCode,
  which
}) {
  const keycode = keyCode ? keyCode : which;
  switch (keycode) {
    case (39):
      box.classList.add('move-right');
      box.classList.remove('move-left');
      break;
    case (37):
      box.classList.add('move-left');
      box.classList.remove('move-right');
      break;
  }
});
.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

.move-right {
  margin-left: 400px;
}

.move-left {
  margin-left: 0px;
}
<div class="box"></div>
ROOT
  • 11,363
  • 5
  • 30
  • 45

3 Answers3

3

You have two instances of transition in your cssCSS

.box {
  ...
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

If you want to specifically have different transitions between margin-left and margin-top, you can combine them.

.box {
  ...
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1), margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}
koralarts
  • 2,062
  • 4
  • 30
  • 48
2

transition should be added once, here is a working snippet:

const box = document.getElementsByClassName('box')[0];

document.addEventListener('keydown', function({keyCode, which}) {
  const keycode = keyCode ? keyCode : which;
  switch(keycode) {
    case(39):
      box.classList.add('move-right');
      box.classList.remove('move-left');
      break;
    case(37):
      box.classList.add('move-left');
      box.classList.remove('move-right');
      break;
  }
});
.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin 0.5s cubic-bezier(0, .7, 0, 1);
}

.move-right {
  margin-left: 400px;
}

.move-left {
  margin-left: 0px;
}
<div class="box"></div>
ROOT
  • 11,363
  • 5
  • 30
  • 45
2

If you look at the css that you have written,

.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

You have 2 transition properties in place, and the transition property get overridden by the next one, which transitions margin-top property.

When the styles are computed the this is what the css rule looks like.

.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

As you have keys with the same type, the last rule wins, in this transition for margin-top and the transition for margin-left is lost.

So either remove the 2nd transition rule or write it as a single rule, will comma separated properties.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105