Archive for July, 2006

Update to onpaste

Friday, July 14th, 2006

As I posted yesterday, onpaste is Internet Explorer’s handler for detecting a user’s pasting into a textarea or input. However, Internet Explorer seems to fire onpaste before the actual paste of text occurs in some circumstances, which makes the whole event irrelevant. Luckily, there’s a quick fix: make onpaste run your function on a timeout.

Here’s a quick example:

function iePasteDelay(){
setTimeout(’pasteIt()’,1)
}
function pasteIt(){
// your paste function
}

and in the code…

<textarea onpaste="iePasteDelay()"></textarea>

That one millisecond delay is enough to force Internet Explorer to run your function after the actual text has been pasted. Problem solved.

Detecting paste into form input

Thursday, July 13th, 2006

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.

I'm Reading…
Search This Site
You are currently browsing the A Modern Fable weblog archives for July, 2006.

AddThis Feed Button

Need great hosting?

Categories