3

I want to simulate keypresses in Javascript. There are no listener for those key presses. For example: The function will trigger key '32' (spacebar) and this should result in scrolling of page like pressing normal spacebar.

I tried keypress trigger from Simulating a Keypress Event from Javascript Console but it didn't worked.

Edit
Key presses are not limited to spacebar only. It can be combined keys like alt+Ctrl+D and the browser should respond to them like keypresses from physical keyboard.

Community
  • 1
  • 1
Dheerendra
  • 1,488
  • 5
  • 19
  • 36

2 Answers2

1

If you're only looking to scroll the document, you can approximate a Spacebar or Pg Dn scroll by using 85% of window.innerHeight - no jQuery needed:

window.scrollBy(0, window.innerHeight * .85);
Ben Grimm
  • 4,316
  • 2
  • 15
  • 24
0

By this way you can bind keypress event to body and identify which key is pressed.

jQuery('body').on('keyup',function(e){ 
     if(e.which == 32) {
          // spacebar pressed, your scroll code here.
     }
}) ; 
shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50