I am coding a JavaScript game, with a moving ball.
I want an alert message when the user manage to click on the moving ball.
It is working right now, but the event is not firing every times. It looks like the ball is moving too fast for the js engine to be able to notice that the ball was indeed clicked.
I am testing on Firefox 18, Windows 7 on a 5 years old cpu.
Here are some bits of my code :
myBall = document.getElementById("myBall");
function move(){
myLeft += 20;
myBall.style.left = myLeft + "px";
}
myTimer = window.setInterval(move, 10);
...
myBall.addEventListener("click", function(){alert("win")});
Is there any way to set a click event listener on a small moving target, that will behave more accurately ? Would jQuery make any difference here?
All right, to solve the problem you’re having, you’ll need to add event listener for
mousedowninstead ofclick.It is because
clickrequires mouse button to go both down and up, and – as @techfoobar noted – it must be done at the same place on the target element (if coords ofmousedownandmouseupare not equal, theclickevent won’t be fired). The ball simply moves too fast to meet the aforementioned condition, hence the problem.