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>
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);
}