Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!