JS style.setProperty not called every time

167 Views Asked by At
Hi, this is my first question on stackoverflow, so please dont roast me more than necessary :)

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

This is the function that is called by the eventListener

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>

https://gifyu.com/image/S7X4m

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!

2

There are 2 best solutions below

0
stepframe On BEST ANSWER

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

1
grimsteel On

I don't have enough reputation to comment, but where are you checking to see if the css var is updated?

The developer tools will only update so often, so even if the css vars are probably being updated correctly you might see a delay there.