Reputation: 21
For some reason the console keeps on saying Uncaught TypeError: Cannot read property 'clientX' of undefined at moveCircle (script.js:5) but the code still works in the browser. Could you explain how that error is appearing in the console?
1 const CIRCLE = document.querySelector(".circle");
2 const BODY = document.body;
3
4 function moveCircle(e) {
5 CIRCLE.style.left = e.clientX + "px";
6 CIRCLE.style.top = e.clientY + "px";
7 }
8
9 BODY.addEventListener("mousemove", moveCircle, false);
10 setInterval(moveCircle, 1);
Upvotes: 0
Views: 884
Reputation: 6501
For these kind of things please use window requestAnimationFrame (rAF), since rAF or setTimeout cannot access event directly, your best choice is to either record the event somewhere and consume it from there, or store the last coordinates and operate on them. Something like this maybe??
https://jsfiddle.net/ibowankenobi/8z5a5sgj/5/
var circle = document.querySelector(".circle");
var pos = [0,0];
document.getElementById("container").addEventListener("mousemove",updatePos,false);
window.requestAnimationFrame(move);
function updatePos(e){
pos[0] = e.clientX || 0;
pos[1] = e.clientY || 0
}
function move(){
var diffX = pos[0] - circle.offsetLeft;
var diffY = pos[1] - circle.offsetTop;
if(diffX) {
circle.style.left = circle.offsetLeft+Math.max(-5,Math.min(diffX/10,5))+"px";
}
if(diffY) {
circle.style.top = circle.offsetTop+Math.max(-5,Math.min(diffY/10,5))+"px";
}
window.requestAnimationFrame(move);
}
Upvotes: 0
Reputation: 53
Function moveCircle
called by setInterval
doesn't have event object.
Function moveCircle
triggered by event mousemove
will work.
Why do you want call moveCircle
by setInterval
?
Upvotes: 1