6

I'm having an issue with jQuery 1.6.4, iOS 5 and the registration of touchstart/touchend events (as stated in the title, obviously).

Take the following code:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="mmpa/jquery-1.6.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var $body = $('body');
            $('<button>').html('test jQuery').bind('touchstart', function() { alert('touchstart'); }).appendTo($body);
        });
    </script>
</head>
<body>
    <button ontouchstart="alert('touchstart');">test pure JS</button>
</body>
</html>

The "pure JS" button shows the alert in iOS 4.3 and iOS 5, but the "jQuery" button only works on iOS 4.3. Tested on iPad/iPhone simulator, 4.3 and 5 ; also tested on real iPhone 4.3, iPhone 5.0, and iPad 5.0. Same reaction if I use a <input type="button"> or even a simple <a> instead of a <button>.

Is it a problem related to jQuery as I believe?

Cyrille
  • 25,014
  • 12
  • 67
  • 90
  • do not use bind('touchstart') and ontouchstart="". Use one of them, and prefer not using inline javascript. – Design by Adrian Oct 07 '11 at 15:10
  • 1
    That was a proof of concept to show that inline JS works when jQuery doesn't. Of course I never, ever use inline JS in real code. – Cyrille Oct 07 '11 at 15:23
  • I was able to produce this error with jQ 1.5.2 and the click event, so perhaps you should modify the title to be something like "jQuery Events on iOS 5" – webXL Oct 19 '11 at 20:58

1 Answers1

8

Answered by a guy on Apple dev forums: I need to bind() only after the element has been added to the DOM, like so:

var btn = $('<a>').html('test jQuery').appendTo($body);
btn.bind('touchstart', function(e) { alert('touchstart'); });
Cyrille
  • 25,014
  • 12
  • 67
  • 90
  • 2
    What happens if you use live() instead of bind()? Any explanation for why it stopped working in iOS 5? – Crashalot Oct 17 '11 at 20:42