Call player.stop(false);
before player.animate(...);
. It will stop currently running and queued animations of the player object.
Handle multiple clicks when making an object move
-
01-07-2022 - |
Question
I have the following:
var player = $('#player');
//Checks to see which key is pressed down
$(window).on('mousedown', function (e) {
console.log(e.offsetX + ', ' + e.offsetY);
player.animate({
left: e.offsetX + 'px',
top: e.offsetY + 'px'
}, 500);
});
What I am trying to achieve is when I click somewhere on the screen, the image moves to that position, but if I click again in the middle of my moving-animation, it's supposed to go to the last place I clicked instead of carrying out the first animation first.
Thank you!
Solution
OTHER TIPS
To handle multiple clicks you need to create a pool, an array of functions controled by another function, so when you click at the body you'll add a new function that move the image.
Below, I show a piece of code, about how to create and push an array of functions:
var listRuns = [],
ind = 0;
$('#btnRun').click(function(){
var message = document.getElementById("txtMsg").value;
listRuns.push(function(){
run(message);
});
});
Then, you need another function that control the execution of this array, as show below:
var runAll = function(){
if (listRuns.length>ind){
listRuns[ind]();
ind++;
}
};
var idInterval = setInterval(function(){
runAll();
},1000);
So, you create a poll of executions, take a look at this example to more detailed information.