How to check if a KeyboardEvent object is in JavaScript?

I want to have a function that takes an event as a parameter and checks if a valid event object has passed.

function doSomething(e){
  if(e is a keyboard event){
   // Proceed
  } else {
    console.log('Error: e is not a KeyboardEvent');
  }
}

typeof ejust returns object. But the debug console shows KeyboardEvent clearly, so you need to read it somehow.

+4
source share
3 answers

as simple as with an operator instanceof:

if (e instanceof KeyboardEvent){
  // it is a keyboard event!
}

Explanations from MDN :

The operator instanceofchecks to see if the object in its prototype chain has the prototype property of the constructor.

, (i) /, . / .

+7

if(e.type == 'keypress')

function doSomething(e){
  if(e.type == 'keypress'){
   // Proceed
  } else {
    console.log('Error: e is not a KeyboardEvent');
  }
}
+2

This will work for your business.

Be careful with input-eventthis, this is not an instance of KeyboardEvent.

function testEventType(e){
	console.log(e.type, e instanceof KeyboardEvent);
}

document.querySelector("#test").addEventListener('keypress', testEventType);
document.querySelector("#test").addEventListener('input', testEventType);
<input id="test"/>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1672575/


All Articles