I have developing an application that records the events and replays them. For that I need to identify what kind of event is being generated because mouse, keyboard and form events behave differently from each other.
Right now i am trying to use:
e instanceof KeyboardEvent but this doesn't seems to be working. What is the better way of identifying to which event family it belongs to?
A basic example for a mouse and keyboard event. You just have to add an eventListener to your desired dom element. And then you have to check if the triggered event e is an instance of MouseEvent or if it is a KeyboardEvent.
const button = document.getElementById('mouse');
button.addEventListener('mousedown', (e) => {
if (e instanceof MouseEvent) {
console.log('a mouse event');
}
});
const inputField = document.getElementById('keyboard');
inputField.addEventListener('keydown', (e) => {
if (e instanceof KeyboardEvent) {
console.log('a keyboard event');
}
});
<button id="mouse">MouseButton</button>
<input id="keyboard">
Using the event.detail allow you to determine if the event was a keypress or mouse event
if (event.detail === 0) {
// keypress event
} else {
// mouse event
}
Read more here - https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail