Reputation: 6472
I have a very simple HTML5 game that works as expected from a regular browser, but when accessed from a browser on an iPhone or iPad, it does not recognize the click event or the touchstart event.
The original code is from a tutorial located here: http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
I have modified it and added a click event which will move the smiley face to wherever you click on the canvas. This click event works fine from Mac and Windows browsers with a mouse: http://iwebss.com/test
But if you access it with an iPhone or iPad, the click event does not work. I also tried adding an additional listener for touchstart, which does not work either.
These are the new listeners I added to the code:
addEventListener("click", mouseClickEvent, false);
function mouseClickEvent(e) {
alert("click event");
mouseClick = true;
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
} else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
addEventListener("touchstart", testEvent, false);
function testEvent(e) {
alert("touchstart event");
}
Any ideas on what I am doing wrong, or how to read iPhone and iPad touch events?
EDIT: I also tried the mousedown event which also does not work.
RESOLVED: I figured it out... see my answer below.
Upvotes: 1
Views: 11340
Reputation: 6472
Ok, I figured it out ... although the event listener works in a regualr browser, for iphone/ipad you need to specifically attach it to the canvas.
So in my given example, I have:
var canvas = document.createElement("canvas");
So this worked in regular browsers, but NOT on iphone/ipad:
addEventListener("click", mouseClickEvent, false);
SOLUTION: This is what I had to do to get it to work on iphone/ipad (add the canvas. in front):
canvas.addEventListener("click", mouseClickEvent, false);
This also worked for the touchstart event as well!
As a side note, I wonder if it matters whether you use touchstart or click event on iphone??
Upvotes: 3
Reputation: 46778
Handlers to attach are:
ontouchstart - a finger goes down.
ontouchmove - a finger moves.
ontouchend - a finger goes up.
ongesturestart - a scale or a rotation starts.
ongesturechange - a scale or a rotation.
ongestureend - a scale or a rotation ends.
Several meta iOS-specific meta tags along with other info here.
Upvotes: 5