Question: How can I ensure that when the target is clicked, the correct and updated value of the left
property is returned? For example, I want it to return 120px if --moved
is applied, and 100px if it is not applied.
Background: Utilizing getComputedStyle, one can retrieve the values of CSS properties assigned to an HTML element. However, in scenarios where elements utilize absolute positioning, it does not function as anticipated.
Example: In the simplified scenario depicted below, upon clicking the target, the --moved
class is either added or removed. Surprisingly, even after this alteration, getComputedStyle
continues to provide the initial value of left
rather than the updated one post-class modification. This anomaly raises concerns on how to obtain the precise CSS values.
Bonus Point: Upon rapid successive clicks on the target, the returned value often appears fractional, deviating from both 100px and 120px. This discrepancy suggests that when working with absolutely positioned items, getComputedStyle
may be returning pixel coordinates rather than the intended CSS values. How might one overcome this dilemma?
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>