Question: In the example below, when the target is clicked how do I return the correct, updated value of the left property? For example, if --moved is applied I'd like it to return 120px. If it is not applied I'd like it to return 100px.
Background: getComputedStyle can be used to return the values of css properties that are applied to an HTML element. However, in the case of elements that use absolute positioning it doesn't work as I had expected.
Example: In the simplified example below when the target is clicked the --moved class is either applied or removed from the target. However, for reasons that I don't understand after --moved is applied or removed getComputedStyle returns the value of left that was correct BEFORE the class was either added or removed. For example, when the target is clicked and --moved is added left is changed to 120px. Yet getComputedStyle still returns the original value of 100px.
Bonus Point: If you click the target rapidly the returned value is often fractional and doesn't return either 100px or 120px. This tells me that when using absolute positioned objects getComputedStyle doesn't return the css value, but in fact returns the current pixel coordinates of the target. How do I get the actual CSS values?
const myTarget = document.querySelector('.target');
const classForMoved = '--moved';
myTarget.addEventListener('click', () => {
const doesTargetContainAdjustment = myTarget.classList.contains(classForMoved);
if (doesTargetContainAdjustment === false) myTarget.classList.add(classForMoved);
if (doesTargetContainAdjustment === true) myTarget.classList.remove(classForMoved);
console.log(getComputedStyle(myTarget).left);
});
.target {
position: absolute;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background-color: red;
transition: all 500ms linear;
}
.--moved {
left: 120px;
}
<div class="target"></div>