I'm trying to set up swipe events for a site I'm working on. Basically, when someone swipes the content container, child div elements of that will change content depending on the page one is on. The actual div "contentwrapper" that I am attaching the swipe listeners to does not change.
To do some animations, I have a previous and next page container that stores content. I removed the ajax function where I populate these for simplicity.
This works when going forwards but when going backwards, I seem to lose the preventDefault behavior and the whole page moves with my finger swipe. This problem only happens intermittently and aways when going backwards.
// Slightly modified code by Dave Dunkin
// http://rabblerule.blogspot.com/2009/08/detecting-swipe-in-webkit.html
function addSwipeListener(el, listener)
{
var startX;
var dx;
var direction;
function cancelTouch()
{
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
startX = null;
startY = null;
direction = null;
}
function onTouchMove(e)
{
if (e.touches.length > 1)
{
cancelTouch();
}
else
{
dx = e.touches[0].pageX - startX;
var dy = e.touches[0].pageY - startY;
if (direction == null)
{
direction = dx;
}
else if ((direction < 0 && dx > 0) || (direction > 0 && dx < 0) || Math.abs(dy) > 400)
{
cancelTouch();
}
}
}
function onTouchEnd(e)
{
cancelTouch();
if (Math.abs(dx) > 30)
{
listener({ target: el, direction: dx > 0 ? 'right' : 'left' });
dx = 0;
}
}
function onTouchStart(e)
{
e.preventDefault();
e.stopPropagation();
if (e.touches.length == 1)
{
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
}
}
el.addEventListener('touchstart', onTouchStart, false);
}
Add Swipe Listener
addSwipeListener(document.getElementById("contentwrapper"), function(e) {
swipePageChange(e);
});
function swipePageChange(e) {
if(e.direction == "left") {
moveforward();
}
if(e.direction == "right") {
movebackward();
}
}
Page Movement Events
function moveforward() {
$("#previouspagecontainer").css("z-index","20");
$("#newpagecontainer").css("z-index","40");
$("#previouspage").html($("#circular").html())
$("#newpagecontainer")[0].style.webkitAnimationName = 'flippageright';
$("#newpagecontainer")[0].addEventListener('webkitAnimationEnd', function() {
$("#currentpagecontainer").css("z-index","30");
$("#newpagecontainer")[0].style.webkitAnimationName = '';
$("#circular").html($("#nextpage").html());
});
return false;
}
function movebackward() {
$("#previouspagecontainer").css("z-index","40");
$("#currentpagecontainer").css("z-index","30");
$("#newpagecontainer").css("z-index","20");
$("#previouspagecontainer")[0].style.webkitAnimationName = 'flippageleft';
$("#previouspagecontainer")[0].addEventListener('webkitAnimationEnd', function() {
$("#previouspagecontainer")[0].style.webkitAnimationName = '';
$("#circular").html($("#previouspage").html());
});
return false;
}