When a click event does not shoot at a moving target

I am coding a javascript moving ball game. I want to receive a warning message when the user manages to click on a moving ball. It works right now, but this event does not shoot every time ... It seems that the ball is moving too fast for the js engine to notice that the ball really hit. I am testing Firefox 18, Windows 7 on a 5 year old processor ...

Here are a few 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 a way to set a click event listener on a small moving target that will behave more accurately? Will jQuery have any meaning here? Thanks.

+4
source share
1 answer

Well, to solve your problem, you need to add an event listener for mousedown instead of click .

This is because click requires the mouse button to move both up and up, and - as @techfoobar noted - it must be executed in the same place on the target element (if the coordinates of mousedown and mouseup not equal, the click event will not running). The ball simply moves too fast to meet the above condition, hence the problem.

+3
source

All Articles