[Vuejs]-How to contextually respond to keyboard input?

2๐Ÿ‘

โœ…

you can get the focused element with document.activeElement, and if it is an text input, i.e. input textarea or contenteditable, just ignore the key, like this:

const onKey = (e) => {

    const inputs = ['INPUT', 'TEXTAREA'];
    
    const isInput = document.activeElement === e.target &&
      (inputs.includes(e.target.tagName) ||
      e.target.hasAttribute('contenteditable'));
      
    if (!isInput && e.code === 'KeyN') {
        active.value = (active.value + 1) % 3;
    }
};
๐Ÿ‘คnโ€“

2๐Ÿ‘

You could validate in your onKey method if the target has a type, since only input tags have type attribute

const onKey = (e) => {
  if (e.target.type !== undefined && e.code === 'KeyN') {
    active.value = (active.value + 1) % 3;
  }
};
๐Ÿ‘คDaniel

Leave a comment