-2

I am working on a WebGL application and I use the spacebar for movement of the camera. The problem is, when I press the spacebar the website also scrolls down. Is there a way to disable this feature?

None of the answers so far works reliably. They work for about a second, then the site scrolls down for a tiny amount of time and then the cycle repeats.

This is my code for the keypresses:

window.addEventListener("keydown", (e) =>  {
    if(e.repeat) { return; }

    if(e.which == 27 || e.which == 9) {
        document.exitPointerLock();
        checkMouse = false;
    }

    if(checkMouse) {
        if(e.which == 87) { forwardPressed = true; }
        if(e.which == 83) { backwardPressed = true; }
        if(e.which == 65) { leftPressed = true; }
        if(e.which == 68) { rightPressed = true; }
        if(e.which == 32) { upPressed = true; event.stopPropagation(); event.preventDefault(); }
        if(e.which == 16) { downPressed = true; }
    }
});

As you can see, for the space key there already is one solution implemented but both types of answers I have gotten so far don't work.

user11914177
  • 805
  • 7
  • 22

2 Answers2

1

You can do it something like this

$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if(keycode == '32') {
        event.preventDefault();
    }
});
0

Add this to your javascript:

let checkMouse = true
window.addEventListener("keydown", (e) =>  {
if(e.repeat) { 

    return; 
}

if(e.which == 27 || e.which == 9) {
    document.exitPointerLock();
    checkMouse = false;
}

if(checkMouse) {
    if(e.which == 87) { forwardPressed = true; }
    if(e.which == 83) { backwardPressed = true; }
    if(e.which == 65) { leftPressed = true; }
    if(e.which == 68) { rightPressed = true; }
    if(e.which == 32) { upPressed = true; event.stopPropagation(); event.preventDefault(); }
    if(e.which == 16) { downPressed = true; }
}
if (e.which == 32) {
    return !(e.keyCode == 32);
}
});

checkMouse wasn't initialised before. It's working fine here.

Priyank-py
  • 319
  • 3
  • 13