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">