Joilson
Joilson

Reputation: 13

scroll event on keydown like down arrow and up arrow

I would like to do the same scroll event as the up arrow and down arrow keys on a website. The code below creates an event "similar" to that of the arrows, but it keeps locking while pressing the keys w and s.

document.addEventListener('keydown', e => {
  if (e.keyCode == 87) {
    window.scrollBy({
      top: -30,
      behavior: 'smooth'
    });
  } else if (e.keyCode == 83) {
    window.scrollBy({
      top: 30,
      behavior: 'smooth'
    });
  }
});

Thanks in advance.

Upvotes: 1

Views: 5667

Answers (2)

LDS
LDS

Reputation: 362

document.addEventListener('keypress', e => {
    if (e.keyCode == 119) {
       
        window.scrollBy({ top: -30, behavior: 'smooth' });
    } 
    else if (e.keyCode == 115) {
        window.scrollBy({ top: 30, behavior: 'smooth' });
    }
});

Upvotes: 1

Colin Smith
Colin Smith

Reputation: 320

I've assumed that the problem is that it's 'locking' for a moment before continuing... the following corrects that problem.

You'll need to set a flag on keydown and unset it on keyup

Then you'll need to have something else perform the action.

 var scrollAmount;


document.addEventListener('keydown', e => {
    if (e.keyCode == 87) {
        scrollAmount = -30
    } 
    else if (e.keyCode == 83) {
        scrollAmount = 30
    }
});

document.addEventListener('keyup', e => {
 scrollAmount = 0;
});

setInterval (function() {
     window.scrollBy({ top: scrollAmount});
},10)

Upvotes: 2

Related Questions