0

I am trying to prevent scrolling when I use arrow keys in my HTML5 game. It is a maze game that you control with arrow keys or buttons on the screen, but whenever I press the 'up' or 'down' keys, it always scrolls.I am using:

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
    } else if(e.keyCode === 38) {
        up();
    } else if(e.keyCode === 37) {
        leftclick();
    } else if(e.keyCode === 39) {
        rightclick();
    }
})

Is this possible with javascript? I want it to be able to scroll with my mouse, but not when I use arrow keys on my keyboard. My game is at http://thomaswd.com/maze. Please help. Thanks!

2

3 Answers 3

2

Use e.preventDefault() to prevent the normal key action from taking place.

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
        e.preventDefault();
    } else if(e.keyCode === 38) {
        up();
        e.preventDefault();
    } else if(e.keyCode === 37) {
        leftclick();
        e.preventDefault();
    } else if(e.keyCode === 39) {
        rightclick();
        e.preventDefault();
    }

})

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, this worked without using the keypress, but I added the e.preventDefault() and it worked
1

Try this:

document.addEventListener('keydown', function(e) {
        if(e.keyCode > 36 && e.keyCode < 41) {
            e.preventDefault();
        }
        if (e.keyCode === 40) {
            down();
        } else if (e.keyCode === 38) {
            up();
        } else if (e.keyCode === 37) {
            leftclick();
        } else if (e.keyCode === 39) {
            rightclick();
        }
        return false;
    }, false);
}

Comments

0

Try to add e.preventDefault(); at the end

1 Comment

at the end of each 'if' statement I mean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.