tags:

views:

111

answers:

1

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.

+3  A: 

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.

William Brendel
Good tip. Why not keypress instead of keyup, keydown?
Sean Hogan
Depending on the browser, the `keypress` event is not triggered in all cases. For example, when the Control key is pressed, `keydown` and `keyup` will be triggered, but `keypress` will *not*. I suppose it doesn't matter in this case, but since the OP's example used `keydown` and `keyup`, I did too. Using `keypress` would work just as well here.
William Brendel
Thank you, very useful tip. Also, I did not know you can simply concatenate event names like this: $("#foo").bind("keyup keydown change paste cut", handler).
Jan Zich