Every time I need to write a piece of JavaScript which monitors an input box, I usually end up doing something like:
$("#field").keyup(myHandler).keydown(myHandler).change(myHandler);
It’s not perfect, but it usually works in most cases, and so I move on. I just happen to have a little bit of time to investigate this properly. Probably the major problem is that is does not catch edits done via mouse (right-click + paste/cut). Also, it’s not really what I want. This captures all cursor movements and other keyboard events which I’m not really interested in. So the question is:
Is there a reliable cross-browser event which is fired every time after the content of an input or textarea changes?
During a brief search, I found the onpropertychange and DOMAttrModified events. But apart from the fact they don’t work in all browsers, they don’t seem to be fired when editing an input or textarea.
It looks like at least the latest versions of Internet Explorer, Firefox, Chrome, and Safari all support the cut
and paste
events, which are triggered immediately after text is cut or pasted in a given input element. The events are triggered by keyboard and mouse interactions. Listening for a combination of these and other events should provide the functionality you are looking for.
$("#foo").bind("keyup keydown change paste cut", handler);
I tested this on a Mac in Firefox 3.6, Chrome 5.0 (dev), and Safari 4, and on Windows in Firefox 3.5 and IE8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With