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 look likes 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 ? Thanks.
All right, to solve the problem you're having, you'll need to add event listener for mousedown
instead of click
.
It is because click
requires 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 of mousedown
and mouseup
are not equal, the click
event won't be fired). The ball simply moves too fast to meet the aforementioned condition, hence the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With