Keyboard and Input Events

Page section: posts

Keyboard Events

..are not so useful for forms since people can copy/paste or use speech recognition to input into forms as well as the keyboard.

They’re more useful for specific actions such as the arrow keys during a game, or keys for a shortcut for instance.

For forms it’s generally better to use the event input which can use text from any of the above ways text is input into a form.

See more on JavaScript.info

Add items

Items

  • item 1
  • item 2
  • item 3
  • item 4
event what it does
keydown press a key down.
keyup release a pressed key.
keypress
focus same as focus in CSS.
blur removes focus from something.
cut an event is fired when a user cuts something.
paste an event is fired when a user pastes something.
change an event is fired when a value from a <select> dropdown changes.
input an event is fired when something is input to a form field.
submit an event is fired when an input submit button is pressed.

Single key only events

If a keydown event is set it means any key will be used to trigger the event. You can limit the keys using an if statement:

document.addEventListener('keydown', () => {
    if (event.key == 'Escape') {
        map.classList.remove('full-screen');
      };
    })
View contents of: /static/js/keyboard-and-input-events.js

const itemInput = document.querySelector('input[type="text"]');
const form = document.querySelector('form');
const select = document.querySelector('select');

// itemInput.addEventListener('keydown', runEvent)
// itemInput.addEventListener('keyup', runEvent)
// itemInput.addEventListener('keypress', runEvent)
itemInput.addEventListener('input', runEvent)

select.addEventListener('change', runEvent);

form.addEventListener('submit', runEvent);

function runEvent(e) {
    // console.log('EVENT TYPE: ' + e.type);
    e.preventDefault();
    console.log(e.target);
    document.getElementById('output').innerHTML = e.target.value ;
};