Running events when a user types into a form is easy. Determining when a user has pasted into the form is a little more difficult. When a user types, onkeyup, onkeydown, and onkeypress are fired, giving you ample time to fire your own event. But, what happens if a user pastes into your textarea, input, or other textfield?
Well, if the user does the old CTRL+V paste, you’re covered: the key events fire. However, if they do the old right-click paste, your need a new handle. Don’t worry, though, Internet Explorer and FireFox (Mozilla) both provide us with event hooks we can use to catch a paste.
Internet Explorer (from 6.0 on down to the 5s) provides us with the aptly named onpaste event. onpaste does exactly what you’d think it would do: fire right when the paste finishes.
FireFox also provides an event hook for text field pastes, and it’s called oninput. oninput fires right when paste finishes, too.
Now, how would we cover all our bases, both keypresses and pastes? We using the following events: onkeyup, onkeydown, onpaste, and oninput. Let’s say we’re building a character counter function; by runinning (and re-running) our counter function on all these actions, we’re covered in any and all cases.
Here’s how our character counter would look when applied to a textarea (I’ll leave the actual counter implementation to you, and sorry for the oddly formatting code snippet):
<textarea onkeyup="countCharacters()"
onkeypress="countCharacters()" oninput="countCharacters()"
onpaste="countCharacters()">
</textarea>
Our events now fire in all the right places.