Reputation: 3276
I'm having trouble with jQuery touch events in iOS.
Here is what I've done:
$(document).ready(function(){
var iX = 0,iY = 0,fX = 0,fY = 0;
document.addEventListener('touchstart', function(e) {
var touch = e.touches[0];
iX = touch.pageX;
iY = touch.pageY;
}, false);
document.addEventListener('touchmove', function(e) {
var touch = e.touches[0];
fX = touch.pageX;
fY = touch.pageY;
}, false);
document.addEventListener('touchcancel', function() {
var dX = fX - iX;
var dY = fY - iY;
var tg = dY/dX;
if(tg < 0) tg = -tg;
if(tg <= 0.5 && fX > iX) rightSwipe()
else if(tg <= 0.5 && fX < iX) leftSwipe()
}, false);
function rightSwipe(){
$("#body").removeClass("bg2");
$("#body").addClass("bg");
}
function leftSwipe(){
$("#body").removeClass("bg");
$("#body").addClass("bg2");
}
});
When you touch your finger into the screen, it saves the finger position. When you move your finger and release it, it saves the last finger position. By simple geometry, it discovers the direction you swiped.
This script works very well on Android 4.1.2 using Google Chrome and Android default browser. When I try it on iOS using Safari, it doesn't work.
Someone can help?
Upvotes: 3
Views: 2117
Reputation: 14429
I haven't seen the touchcancel
event on Mobile Safari on the iPad. Have you tried using touchend
instead? Perhaps this:
function upHandler(event) {
var dX = fX - iX;
var dY = fY - iY;
var tg = dY / dX;
if (tg < 0) tg = -tg;
if (tg <= 0.5 && fX > iX) rightSwipe()
else if (tg <= 0.5 && fX < iX) leftSwipe()
}
document.addEventListener('touchcancel', upHandler, false);
document.addEventListener('touchend', upHandler, false);
If you use jQuery, you can replace this:
document.addEventListener('touchcancel', upHandler, false);
document.addEventListener('touchend', upHandler, false);
With:
$(document).on('touchcancel, touchend', upHandler);
Upvotes: 3