9

I want to have a function that accepts event as a parameter and checks if valid event object is passed.

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

typeof e just returns object. But debug console clearly shows KeyboardEvent, so it must be readable somehow.

3 Answers 3

22

Vanilla JS

as simple as that with the instanceof operator:

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

Explainations from MDN :

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

Note that this operator can be messy when dealing with multiple (i)frame/windows because they have different context and different builtins. but in the same window/frame, it's not a problem.

Example :

document.querySelector("#foo").addEventListener("keydown", (event)=>{
  console.log("event instanceof KeyboardEvent : ",event instanceof KeyboardEvent);
});
<label for="foo">edit input to check event type</label>
<input type="text" id="foo">

jQuery

jQuery wraps native events with its own implementation :

jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

source

But Note that the native event is still accessible via event.originalEvent. And you can still test event.type (event.type==="keyup" || event.type==="keydown" || event.type === "keypress").

Example :

$("#foo").on("keyup", (jqEvent) => {
  console.log("jqEvent instanceof KeyboardEvent : ", jqEvent instanceof KeyboardEvent); //false
  console.log("jqEvent.originalEvent instanceof KeyboardEvent : ", jqEvent.originalEvent instanceof KeyboardEvent); //true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="foo">edit input to check event type</label>
<input type="text" id="foo">

Sign up to request clarification or add additional context in comments.

6 Comments

In Chrome when I put console.log(e instanceof InputEvent) in my input event handler, it returns false. Any ideas why?
I found out it's because the YUI rich text editor widget is using custom events.
But, when you try to type check the event, this won't be helpful. See this fiddle. The type of the incoming event is Object (which is acceptable), but not KeyboardEvent (which is confusing). Any idea why?
@RomeoSierra Because jQuery wraps native events with its own event type. You can test jqEvent.originalEvent though.
@RomeoSierra I added a jQuery section to my answer
|
3

This would work for your case.

Be careful with input-event it 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"/>

3 Comments

DomeTune, thanks for the warning. Can an input be generated by keyboard?
@Alph.Dev Yes KeyboardEvent inherits from InputEvent Event<---InputEvent<---KeyboardEvent. so KeyboardEvents are InputEvents.
@Alph.Dev a n00dl3 allready pointed out you can check for InputEvent, the Event includes ShortCuts as well. CTRL+V, CTRL+X, ...
1

try this if(e.type == 'keypress')

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

1 Comment

Yes, I am aware of that. I can always use (e.type == 'keypress' || e.type == 'keydown' || e.type == 'keyup'), but that is messy. I'm trying to find a way to use KeyboardEvent key word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.