i have a function called by a eventListener on mousemove. the function writes the mouse coords to two css variables. Sadly, this does not update on every call of the function for some reason
var textMoved = false;
var initialCoordinates = {x: 0, y: 0};
var documentRoot = document.querySelector(":root");
// ...
document.addEventListener("mousemove", animateType)
function animateType(e) {
//check if its the first time the mouse is moving
if (!textMoved) {
// if yes, set the initial coordinates
textMoved = true;
initialCoordinates = {
x: (e.clientX / window.innerWidth) * 100,
y: (e.clientY / window.innerHeight) * 100,
};
console.log("initial coordinates", initialCoordinates)
} else {
// if not, calculate a offset from the initial coordinates so the text doesn't flick when the mouse is moved the first time
const {clientX, clientY} = e;
const x = initialCoordinates.x - (clientX / window.innerWidth) * 100;
const y = initialCoordinates.y - (clientY / window.innerHeight) * 100;
documentRoot.style.setProperty("--entry-offset-1", x + "px");
documentRoot.style.setProperty("--entry-offset-2", y + "px");
console.log("offset", x, y);
}
}
div {
background-color: red;
height: 20px;
width: 20px;
position: absolute;
transform: translate(var(--entry-offset-1), var(--entry-offset-2));
}
body {
padding: 150px;
}
<div>
</div>
Somehow, the faster I move my mouse, the laggier it gets. Sometimes its like half a second until the css var is updated. The function is definetly called correctly, the console.log is consistant with the mouse movement. Also, there is no console error or something like that
Why is this not overwriting the css var every time the function is called?
Thanks in advance!
I found the issue. It was caused by a css "animation-delay" on a totally unrelated element in the DOM. When i removed it, it worked perfectly