Last active
August 29, 2015 14:23
-
-
Save Alex1990/0eeeccbdde88ee5813ef to your computer and use it in GitHub Desktop.
A simple cross browser input event.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * A simple cross browser input event. | |
| */ | |
| function input(node, callback) { | |
| var doc = document; | |
| var isIE9 = doc.documentMode && (doc.documentMode === 9); | |
| var isInputSupported = ('oninput' in node) && !isIE9; | |
| var inputValue = node.value; | |
| var addEvent = function(elem, type, listener) { | |
| elem.attachEvent('on' + type, listener); | |
| }; | |
| var removeEvent = function(elem, type, listener) { | |
| elem.detachEvent('on' + type, listener); | |
| }; | |
| if (isInputSupported) { | |
| node.addEventListener('input', callback, false); | |
| } else { | |
| var inputHandler = function(e) { | |
| if (node.value !== inputValue) { | |
| inputValue = node.value; | |
| callback.call(node, e); | |
| } | |
| }; | |
| var propertychangeHandler = function(e) { | |
| if (e.propertyName === 'value') { | |
| inputHandler.call(node, e); | |
| } | |
| }; | |
| addEvent(node, 'propertychange', propertychangeHandler); | |
| if (isIE9) { | |
| var focusHandler = function(e) { | |
| if (e.type === 'focus') { | |
| addEvent(doc, 'selectionchange', inputHandler); | |
| } else { | |
| removeEvent(doc, 'selectionchange', inputHandler); | |
| } | |
| }; | |
| addEvent(node, 'focus', focusHandler); | |
| addEvent(node, 'blur', focusHandler); | |
| } | |
| var nextTickInputHandler = function(e) { | |
| var that = this; | |
| setTimeout(function() { | |
| inputHandler.call(that, e); | |
| }); | |
| } | |
| addEvent(node, 'keydown', nextTickInputHandler); | |
| addEvent(node, 'cut', nextTickInputHandler); | |
| addEvent(node, 'paste', nextTickInputHandler); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment