Search code examples
jqueryipadmobile-safari

jQuery click handler not called on iPad


I have a project using jQuery and a lot of dynamically-generated content. There is a click handler on the upper-left-most element– the "initiative" score– and it works fine on desktop Safari but isn't called at all on Mobile Safari; the gray overlay never appears and no action is taken. It's the same story with the click handler on the Hit Points area (the 172 at right) and the status ("Add Status Effect" at bottom; confirm; it appears over the portrait): all work on desktop but not mobile Safari.

I've reduced the code to the following:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
      $(function() {
        $('#dynamic').click(function() {alert("works")});
        $('#dynamic-with-onclick').click(function() {alert("works")});
        $('#dynamic-with-dynamic-onclick').click(function() {alert("works")}).attr('onclick', '');
      })
    </script>
  </head>
  <body>
    <ul>
      <li id='static' onclick='alert("works")'>If there's an onclick it's called</li>
      <li id='dynamic'>And if there's no onclick the iPad won't see other click events</li>
      <li id='dynamic-with-onclick' onclick=''>But if there is one all events are called</li>
      <li id='dynamic-with-dynamic-onclick'>And if we add one everything works</li>
    </ul>
  </body>
</html>

Update

This appears to be much simpler now than when I originally asked this question 10 months ago; using modern Mobile Safari all click handlers will register as normal. So go forth and just use $(...).click(function() {})!


Solution

  • We could do the hackish thing and just add onclick to anything we want clickable. But the "right" way to do this seems to be using an iPad-appropriate event:

    var hitEvent = 'ontouchstart' in document.documentElement
      ? 'touchstart'
      : 'click';
    $('#dynamic').bind(hitEvent, function() {alert("works")});
    $('#dynamic-with-onclick').bind(hitEvent, function() {alert("works")});
    $('#dynamic-with-dynamic-onclick').bind(hitEvent, function() {alert("works")}).attr('onclick', '');
    

    Another way to do it is to bind to multiple events and be happy with whichever one gets called.

    I'm currently using the first solution; I might try the other one, as I think it's cleaner.