Friday, August 3rd, 2007

Safari on the iPhone update fixes and breaks events

Category: iPhone

There was a lot of discussion around events and Safari on the iPhone, when it first came out.

Neil Roberts of SitePen has noted that with the iPhone 1.0.1 update, we have some fixes, and some new issues:

I’ve been following John Gruber on Twitter, who just noticed that the iPhone update (1.0.1) now updates Safari with the ability to send key events. Fantastic! 2 steps forward.

But, onkeyup is broken. You see, the onkeyup event is supposed to be called after a key event has officially propagated through the page. This is very important, because by the time onkeyup gets called, the page should have adjusted itself for this newly inserted character. For example, in a text input box, when you press a key it doesn’t show up in that input box until after onkeydown and onkeypress have been called, but does show up before onkeyup is called. Pretty much the whole reason that onkeyup hook exists at all, is so that you can be notified after this change has happened. The iPhone sends onkeyup before the page has been updated. 1 step back.

What this means is that sites that rely on using the onkeyup event to tell what is in their text entry box will break. There is a simple solution though! (other than having to find the key value in the event object) Just use setTimeout, with a timeout of 0 and you’ll be able to see the proper value. For example:

javascript

  1. input.onkeyup = function(e) {
  2.     setTimeout(function(){ alert(e.target.value); }, 0);
  3. }

Posted by Dion Almaer at 12:52 am
6 Comments

+++--
3.9 rating from 20 votes

6 Comments »

Comments feed TrackBack URI

Some time ago, I have also to use this trick on IE6.
The problem was not easily repoducible and occured only when the user was entering some text very quickly.
But it was the same issue: the text.value was not yet updated just after the last event.

Comment by arnaud — August 3, 2007

Some things never change. For 20 years, the classic cure-all for Windows timing problems has been the moral equivalent of setTimeout( fn, 0 ):

PostMessage( my_hwnd, MY_MESSAGE, 0, 0 );

Comment by Michael Geary — August 3, 2007

No regression tests at Apple or an incomplete test suite. I’d like to bet on the latter and hope they read Ajaxian :-)

Comment by Paolo Montrasio — August 3, 2007

Nice work around thanks.

Comment by justin — August 3, 2007

I hope that apple will fix this and some of the other stability issues in safari in their next release

Comment by Joshua Giese — August 3, 2007

This is exactly the same behavior — and fix — given by IE 6’s (haven’t checked 7) onpaste event. It’s a really odd bug in implementation; how did this stuff make it through testing?

Comment by Adam McIntyre — August 3, 2007

Leave a comment

You must be logged in to post a comment.