[JavaScript] oninput and onpropertychange Event Alternative


If we want to detect the content change of HTML input elements, like textarea, input:text, input:password, etc., we can use oninput event of HTML input elements. The oninput event, however, (and onpropertychange event in IE) is a disaster for web developers. Becasue

  • The oninput event is not supported in IE6, IE7, and IE8.
  • Even oninput event is supported in IE9, it is still buggy.

Although we can use onpropertychange event in IE browser, it is still very difficult to maintain a consistent behavior. So here comes the question:

How do we detect the content change of HTML input elements in a cross-browser and consistent way?

The solution is inspired by the library in reference [3]. It is simple, use JavaScript built-in setTimeout or setInterval function to periodically check the content of input elements, and if the content changes, then an event handler function is fired to handle this event. I wrote the following example to demonstrate the solution:

Demo

polling.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript oninput and onpropertychangte Event Alternative</title>
</head>
<body>

<input id="input" type="text">
<div id="info">Type something in above input.</div>

<script src="polling.js"></script>
<script type="text/javascript">
  // focus to input element.
  document.getElementById('input').focus();

  // start to polling input element
  polling();
</script>
</body>
</html>
polling.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * event handler to be fired if the content of input element have changed.
 */
function eventHandler() {
  // write your own event handler here.
  document.getElementById('info').innerHTML = 'input content changed to ' +
    document.getElementById('input').value;
}

/**
 * Variable which keeps track of the content of input element
 * @type {string}
 */
INPUT_CONTENT = '';

/**
 * Check input element periodically.
 */
polling = function() {
  if (INPUT_CONTENT != document.getElementById('input').value)
    eventHandler();

  // update INPUT_CONTENT
  INPUT_CONTENT = document.getElementById('input').value;

  // polling interval: 500ms.
  // you can change the polling interval to fit your need.
  setTimeout(polling, 500);
};

References:

[1]oninput event | input event - Dottoro
[2]onpropertychange event | propertychange event - Dottoro
[3]suggest.js - Input Suggest Library