setTimeout(() => {
var x = element.getBoundingClientRect().x;
var y = element.getBoundingClientRect().y;
element.style.left = x + 'px';
element.style.top = y + 'px';
element.style.position = 'fixed';
window.scrollX; // (comment out this line to break the code!)
element.style.left = parseFloat(element.style.left) + 30 + 'px';
}, 1000);
#element {
background-color: #fa4;
width: 100px;
height: 100px;
position: static;
transition: 1s;
}
<html>
<body>
<div id="element"></div>
</body>
</html>
I want to take a static
positioned element and changed to fixed
in the same place, then change the left
value to move it around. The element's style.transition
property is set to 1s
.
The following does not work in chrome/safari/firefox (the element jumps to its new position instead of smoothly transitioning):
let x = element.getBoundingClientRect().x;
let y = element.getBoundingClientRect().y;
element.style.left = x + 'px';
element.style.top = y + 'px';
element.style.position = 'fixed';
element.style.left = parseFloat(element.style.left) - 500 + 'px';
On the other hand, the following slightly different code does work:
element.style.left = element.getBoundingClientRect().x + 'px';
element.style.top = element.getBoundingClientRect().y + 'px';
element.style.position = 'fixed';
element.style.left = parseFloat(element.style.left) - 500 + 'px';
In fact, even this works:
let x = element.getBoundingClientRect().x;
element.style.left = x + 'px';
element.style.top = element.getBoundingClientRect().y + 'px';
element.style.position = 'fixed';
element.style.left = parseFloat(element.style.left) - 500 + 'px';
Or this (!!):
let x = element.getBoundingClientRect().x;
let y = element.getBoundingClientRect().y;
element.style.left = x + 'px';
element.style.top = y + 'px';
element.style.position = 'fixed';
window.scrollX;
element.style.left = parseFloat(element.style.left) - 500 + 'px';
I am trying to deepen my understanding of javascript. Can someone explain to me what causes the last 3 examples to work?
Obviously, I can guess this is something to do with the browser being forced to "recognize" the new left
and top
values before the left
value is changed again in the last line, but I would like to know exactly why and how this is happening, and also if this phenonemon is known by some name.