Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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):

about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda