I would like to be able to read the value of a CSS property in the middle of a transition before it is fully executed. Is that possible? So if during a transition from 0% to
Yes, it's possible. The corresponding property on the object returned by getComputedStyle will change gradually over the course of a transition, as shown in this demo:
const box = document.getElementById('box'),
turnBlueButton = document.getElementById('turnblue'),
turnPinkButton = document.getElementById('turnpink'),
computedStyleValueSpan = document.getElementById('computedstylevalue');
turnBlueButton.onclick = () => {
box.classList.add('blue');
box.classList.remove('pink');
}
turnPinkButton.onclick = () => {
box.classList.add('pink');
box.classList.remove('blue');
}
const computedStyleObj = getComputedStyle(box);
setInterval(() => {
computedStyleValueSpan.textContent = computedStyleObj.backgroundColor;
}, 50);
#box {
width:50px;
height:50px;
transition: background-color 10s;
}
.pink {
background: pink;
}
.blue {
background: blue;
}
getComputedStyle(box).backgroundColor:
This behaviour is required by spec. https://www.w3.org/TR/css-transitions-1/#transitions- states:
The computed value of a property transitions over time from the old value to the new value. Therefore if a script queries the computed value of a property (or other data depending on it) as it is transitioning, it will see an intermediate value that represents the current animated value of the property.
While the Mozilla docs seem to say that getComputedStyle would return either the start or the end value, they seem wrong, at least for WebKit. WebKit-based browsers' getComputedStyle implementation seems to return intermediate values.
(Hat tip to https://stackoverflow.com/users/27862/user123444555621 for their comment pointing out the relevant spec passage.)