Max Koretskyi
Max Koretskyi

Reputation: 105497

Why is animation (transition) not applied the first time the property is set

Here is a simple setup with a box moving using left property to the right. The property is updated by a button click. Why is transition animation not applied the first time I click on the button?

document.addEventListener('DOMContentLoaded', () => {
  const box = document.querySelector('.box');
  const button = document.querySelector('button');
  button.addEventListener('click', () => {
    const current = parseInt(box.style.left);
    box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
  });
})
.box {
  width: 100px;
  height: 100px;
  background: green;
  position: relative;
  transition: left 1s;
}
<button>Click me!</button>
<div class="box"></div>

Upvotes: 1

Views: 39

Answers (3)

notrota
notrota

Reputation: 1088

As "left" property is intialized as "auto", no transitions can be applied. Instead try this:

document.addEventListener('DOMContentLoaded', () => {
    const box = document.querySelector('.box');
    const button = document.querySelector('button');
    button.addEventListener('click', () => {
        const current = parseInt(box.style.left);
        box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
    });
})
.box {
   left: 0;
   width: 100px;
   height: 100px;
   background: green;
   position: relative;
   transition: left 1s;
}
<button>Click me!</button>
<div class="box"></div>

Upvotes: 1

Walk
Walk

Reputation: 757

Start with some initial value for left.

document.addEventListener('DOMContentLoaded', () => {
    const box = document.querySelector('.box');
    const button = document.querySelector('button');
    button.addEventListener('click', () => {
        const current = parseInt(box.style.left);
        box.style.left = (isNaN(current) ? 0 : current) + 50 + "px";
    });
})
.box {
            left: 0;
            width: 100px;
            height: 100px;
            background: green;
            position: relative;
            transition: left 1s;
        }
<button>Click me!</button>
<div class="box"></div>

Upvotes: 2

Quentin
Quentin

Reputation: 943569

The initial value of left is auto and auto is not a transitionable value.

You would need to explicitly set left: 0 to have a transition then.

Upvotes: 5

Related Questions