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?
CodePudding user response:
It does not seem to have any issues. It's working fine. I changed the code to make it scroll up and down when pressed W and D. Run the snippet below to check.
document.body.onkeyup = function(e) {
var code = e.keyCode;
if(code === 87) { // W
window.scrollTo(document.body.scrollLeft,
document.body.scrollTop 500);
}
if(code === 68) { // D
window.scrollTo(document.body.scrollRight,
document.body.scrollBottom 500);
}
};
.container{
background-color:red;
height:1000px
}
.container2{
background-color:blue;
height:100vh
}
<div class='container'>
test
<div>
<div class='container2'>
test
<div>
CodePudding user response:
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):
