Search code examples
javascriptimageoffsetonmousedown

Handle multiple clicks when making an object move


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.

Full fiddle

Thank you!


Solution

  • Call player.stop(false); before player.animate(...);. It will stop currently running and queued animations of the player object.