Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keydown pauses after first keyress, and subsequent keypresses

Go Here

Use UP and DOWN keys

When I press a key, the red box moves down, pauses, then moves the rest.

How do I remove the pause?

like image 503
AlexMorley-Finch Avatar asked Jun 12 '12 12:06

AlexMorley-Finch


1 Answers

You should follow keydown as well as keyup and use an interval to move the paddle more smoothly.

Demo: http://jsfiddle.net/M7TKc/16/

var paddle = $("#paddle");
paddle.css({backgroundColor: "red", height:"100px", width:"25px", position: "absolute"});

var paddle_y = 0,
    moving = 0;  /* added */

draw_paddle();

window.setInterval(function () {  /* added */
    if (moving != 0) {
        paddle_y += moving;
        draw_paddle();
    }}, 100);

function move_down(){
    moving = -10;
}
function move_up(){
    moving = 10;
}

function draw_paddle(){
    paddle.css({top: paddle_y+"px"});
}

$(document).keypress(function(e) {
    if(e.which == 13) {
        // stop on "ENTER"
        moving = 0;
    }
});
$(document).keydown(function(e){  /* changed */
    if (e.keyCode == 38)
        move_down();
    else if (e.keyCode == 40)
        move_up();

});

$(document).keyup(function(e){  /* added */
    if (e.keyCode == 38 || e.keyCode == 40)
        moving = 0;
});
like image 188
Marcel Korpel Avatar answered Oct 31 '22 19:10

Marcel Korpel