Reputation: 105497
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
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
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
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