Using the oninput event handler with onkeyup/onkeydown as its fallback · Mathias Bynens

HTML5 standardizes the oninput event handler, which should be used to detect user input in JavaScript. Sure, you could use onkeydown or onkeyup instead, but those were never really designed for this particular use case, and it shows.

Luckily, all modern browsers support oninput, IE9 included. For older browsers it’s a good idea to fall back to the keydown event, for example. Unfortunately, detecting oninput support isn’t as straight-forward as you’d think. I assumed this JavaScript snippet would return true or false, depending on whether oninput is supported or not:

'oninput' in document.createElement('input');

This works correctly in most browsers, but not in Firefox (see bug #414853 (now fixed)). While it’s still possible to write a working feature test for oninput, it’s really cumbersome.

Besides, there’s no need to feature test — just bind handlers to both the input and keydown events, and then remove the onkeydown handler as soon as the oninput handler fires. Here’s a simple example, DOM0-style:

someElement.oninput = function() {
this.onkeydown = null;
// Your code goes here
};
someElement.onkeydown = function() {
// Your code goes here
};

The keydown event will only fire once (since it fires before oninput) – after that, only oninput will be used. That’s not ideal, but it sure beats adding lines and lines of code just to properly detect oninput support in all browsers.

A simple demo is available. Note that the same pattern can be applied for any event handler that has a lesser alternative in older browsers.