views:

179

answers:

2

This function works perfectly on IE, Firefox and Chrome but when on the iPhone, it will only work when clicking on a <img>. Clicking on the page (anywhere but on a img) wont fire the event.

$(document).ready(function () {
  $(document).click(function (e) {
    fire(e);
  });
});

function fire(e) { alert('hi'); }

The HTML part is extremely basic and shouldnt be a problem.

Any ideas?

+1  A: 

Use jQTouch instead - its jQuery's mobile version

lock
The official mobile version of jQuery is [jQuery Mobile](http://jquerymobile.com/) (but jQTouch is also pretty good).
BoltClock
is it downloadable already? last time i heard it was still conceptual
lock
Sadly, it did not work. I did only include the library without changing my javascript. It seems like jQTouch should overload the $(document).click function.
Garrows
A: 

Adding in the following code works.

The problem is iPhones dont raise click events. They raise "touch" events. Thanks very much apple. Why couldn't they just keep it standard like everyone else? Anyway thanks Nico for the tip.

Credit to: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript

$(document).ready(function () {
  init();
  $(document).click(function (e) {
    fire(e);
  });
});

function fire(e) { alert('hi'); }

function touchHandler(event)
{
    var touches = event.changedTouches,
    first = touches[0],
    type = "";
     switch(event.type)
    {
       case "touchstart": type = "mousedown"; break;
       case "touchmove":  type="mousemove"; break;        
       case "touchend":   type="mouseup"; break;
       default: return;
    }

         //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
         //           screenX, screenY, clientX, clientY, ctrlKey, 
        //           altKey, shiftKey, metaKey, button, relatedTarget);

      var simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);

first.target.dispatchEvent(simulatedEvent);
   event.preventDefault();
}

function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}
Garrows