I am currently working with a moving div in JavaScript that continues to move for a period of time after the key is released. I am looking for a way to immediately stop the animation upon releasing the key.
The animation is controlled by a switch statement using character codes. Can I integrate a keyup function within this switch statement?
$(".sprite2").hide();
$(document).keydown(function(key) {
switch(key.which) {
// a
case 65:
$(".sprite2").hide();
$(".sprite").show();
$(".sprite").animate({left: "-=10px"}, 'fast');
$(".sprite2").animate({left: "-=10px"}, 'fast');
break;
// w
case 87:
$(".sprite").animate({top: "-=10px"}, 'fast');
$(".sprite2").animate({top: "-=10px"}, 'fast');
break;
// d
case 68:
$(".sprite2").show();
$(".sprite").hide();
$(".sprite2").animate({left: "+=10px"}, 'fast');
$(".sprite").animate({left: "+=10px"}, 'fast');
break;
// s
case 83:
$(".sprite").animate({top: "+=10px"}, 'fast');
$(".sprite2").animate({top: "+=10px"}, 'fast');
break;
case onkeyup:
$(".sprite").animate()
}
});
});
The 'sprite' refers to the HTML element(s).
I encountered issues with the .add/removeClass functions, and resolved it by incorporating a second element and toggling their visibility based on the desired action.
Both elements are identical, but one is mirrored horizontally when moving in the opposite direction to simulate forward movement.