Mathi
Mathi

Reputation: 171

Trigger keypress event with event listener WITHOUT jquery

I want to trigger a keypress event as a reaction to an event listener without using jQuery

let arrow = document.querySelector("#arrow");
//When you click on the arrow
arrow.addEventListener('click', function(e){
// It triggers a keypress (down)
  	$(document).trigger(keypressing);
  });

[EDIT] I tried this out, but doesn't seem to trigger the simulated keypress :

let arrow = document.querySelector(".scroll-down");


arrow.addEventListener('click', function(e){
console.log('simulating the keypress of down arrow')
document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));
});


$(window).bind('keypress', function(event) {
	if (event.key == 'x') { 
	console.log('its working with x')
}
});

Upvotes: 1

Views: 3112

Answers (1)

Norbert Bartko
Norbert Bartko

Reputation: 2632

You can use dispatchEvent to trigger event.
Example: trigger keypress with key x

document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'x'}));

docs


This worked for me to trigger key down event:

// Create listener 
document.addEventListener('keydown', () => { console.log('test')})

// Create event
const keyboardEvent = document.createEvent('KeyboardEvent');
const initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';

keyboardEvent[initMethod](
  'keydown', // event type: keydown, keyup, keypress
  true,      // bubbles
  true,      // cancelable
  window,    // view: should be window
  false,     // ctrlKey
  false,     // altKey
  false,     // shiftKey
  false,     // metaKey
  40,        // keyCode: unsigned long - the virtual key code, else 0
  0          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);

// Fire event
document.dispatchEvent(keyboardEvent);

Upvotes: 2

Related Questions