'Javascript Scroll page on specific Keyboard Key

When I hold/press the 'w' key on my keyboard, the whole page should scroll up. When I press the 'd' key, it scrolls down. Except when I am in an input field, because otherwise I would scroll up/down when I want to enter W/D letters.

This would be the code to scroll down when pressing W. 87 = W on Keyboard (code doesnt work correctly)

document.body.onkeyup = function(e) {
    var code = e.keyCode;
    if(code === 87) {
        window.scrollTo(document.body.scrollLeft,
                        document.body.scrollBottom + 500);
    }
};

How do I do this? And is there a way to scroll smooth so I don't click the keys, I can hold them?



Solution 1:[1]

code works correctly, to scroll only if the input is not focused you can check for inputElement !== document.activeElement. To scroll smoothly up you should do this.

document.body.onkeyup = function(e) {
    const inputElement = document.getElementById('myinput');
    var code = e.keyCode;
    console.log(code);
    if(code === 87 && (inputElement !== document.activeElement)) {
        window.scrollTo(0, 0);
        console.log('scrolling');
    }
};
html {
  scroll-behavior: smooth;
}
<input id='myinput' ></input>

Add scroll-behavior: smooth to the <html> element to enable smooth scrolling for the whole page (note: it is also possible to add it to a specific element/scroll container):

Solution 2:[2]

I have fixed the code now it will scroll Along Y axis when you press W/D

var scrollY = 0;
window.addEventListener("keydown", function(e){
    var code = e.keyCode;
    if(code === 87) { // W
       scrollY += 20;
       window.scrollTo(0, scrollY);
    }
    if(code === 68) { // D
       scrollY -= 20;
       window.scrollTo(0,scrollY);
    }
});
.container{
    background-color:red;
    height:1000px
}

.container2{
    background-color:blue;
    height:100vh
}
<div class='container'>
    test
<div>

<div class='container2'>
    test
<div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2