Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On click event not firing on moving target

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.

like image 883
Jean Avatar asked Feb 10 '13 08:02

Jean


1 Answers

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.

like image 59
wassup Avatar answered Oct 14 '22 01:10

wassup