how to show image after swipe in jquery? - javascript

I make a demo in which I show images using next and previous button .
https://jsfiddle.net/uvsb6asa/6/.
I try to make same demo using swipeleft and swiperight
here is my code
https://jsbin.com/fupowilawo/edit?html,css,js,output
can we do the same functionality using swipeleft and swipe right ?
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
} else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
sliders.goToNext();
} else if ( swipeDirection == 'right' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'up' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'down' ) {
sliders.goToNext();
}
}

Related

Won't scroll up when I use this swiping listener

if(window.location.pathname == '/'){
var direc; //swipe direction var
function detectswipe(el,func) {
swipe_det = new Object();
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
var min_x = 40; //min x swipe for horizontal swipe
var max_y = 60; //max y difference for horizontal swipe
direc = "";
ele = document.getElementById(el);
ele.addEventListener('touchstart',function(e){
var t = e.touches[0];
swipe_det.sX = t.screenX;
swipe_det.sY = t.screenY;
},false);
ele.addEventListener('touchmove',function(e){
e.preventDefault();
var t = e.touches[0];
swipe_det.eX = t.screenX;
swipe_det.eY = t.screenY;
},false);
ele.addEventListener('touchend',function(e){
//horizontal detection
if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
if(swipe_det.eX > swipe_det.sX) direc = "r";
else direc = "l";
}
if (direc != "") {
if(typeof func == 'function') func(el,direc);
}
direc = "";
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
},false);
}
jQuery(document).ready(function ($) {
var timer = setInterval(function () {
moveRight();
}, 5500); //keeps the slideshow moving
I can't get the page to scroll up or down with swiping with this function. It's supposed to be a left-right swipe detection. It obviously still scrolls when it's not listening for a touch/swipe. Any help would be greatly appreciated!
Try this, it's very simple but it might help. https://jsfiddle.net/kyb3Lkqd/
var startingLocation = {x: 0, y:0};
$(document).on("touchstart", "#swp", function(e){
console.log(e);
startingLocation = {
x: e.touches[0].clientX,
y: e.touches[0].clientY
};
});
$(document).on("touchmove", "#swp", function(e){
console.log(e, e.touches[0].clientX, e.touches[0].clientY);
if (startingLocation.x < e.touches[0].clientX){
console.log('swiping right!');
} else if (startingLocation.x > e.touches[0].clientX){
console.log('swiping left!');
}
});
It's incredibly simple; I'm almost embarrassed I didn't see it there in the beginning. In the original I had e.preventDefault(); to disable horizontal scrolling when the element was swiped. I don't need that anymore (I think) because I have overflow: hidden enable; which make that line redundant. Removing that makes it work flawlessly.

Adding transition animations with Jquery Mobile on <div> tags

may I remind you before answering that I'm a complete imbecile on Javascript.
I was provided a script to enable swipe navigation on my Jquery Mobile Site by Padilicious. It works by placing these functions, as I understand, on a div tag:
<div data-role="page" data-theme="a" id="swipeBox" ontouchstart="touchStart(event,'swipeBox');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);" style="position:relative;width:100%;height:100%;">
Now my problem is that data-transition on Jquery Mobile only works on tags or buttons. How do I add data-transition, or at least entrance and exit transitions, on a tag?
If you guys also need the JS for the swipe navigation script, here it is:
// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM
// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
} else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
}
}
Note that the following are the ones responsible for redirecting to another page:
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
window.location.href = "gallery.html";
}
My main agenda is only on adding a sliding animations on page transitions. Doesn't matter on how I should do it. Thanks, Love ya!
No need to write that much code.Try following code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"/>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageOne">
<div role="main" class="ui-content">
Page One
<br>
Go to page Two
</div>
</div>
<div data-role="page" id="pageTwo">
<div role="main" class="ui-content">
Page Two
<br>
Go to page One
</div>
</div>
</body>
</html>

HTML Element Height Keeps Incrementing by the Second

Purchased an off the shelf theme for my portfolio site (yes, yes...I'm too busy to design my own right now lol). Anyway I seem to be having an issue, and I have no idea when it started, where my html height keeps growing by 30-60px every 1-2sec.
I've tried viewing the console, however I can't find anything that's triggering this. I'm assuming that some funking Javascript is at play, and need help possibly tracking it down.
Anyone wanna lend a hand here...?
My Site
UPDATE: It seems to be caused by the smoothscroll.js file. Can any JS pro help me find the offending line of code?
// SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 800; // [px]
var stepsize = 80; // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
var pulseAlgorithm = true;
var pulseScale = 8;
var pulseNormalize = 1;
// Acceleration
var acceleration = true;
var accelDelta = 10; // 20
var accelMax = 1; // 1
// Keyboard Settings
var keyboardsupport = true; // option
var disableKeyboard = false; // other reasons
var arrowscroll = 50; // [px]
// Excluded pages
var exclude = "";
var disabled = false;
// Other Variables
var frame = false;
var direction = { x: 0, y: 0 };
var initdone = false;
var fixedback = true;
var root = document.documentElement;
var activeElement;
var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (!document.body) return;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// check compat mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
initdone = true;
// Checks if this script is running in a frame
if (top != self) {
frame = true;
}
/**
* This fixes a bug where the areas left and right to
* the content does not trigger the onmousewheel event
* on some pages. e.g.: html, body { height: 100% }
*/
else if (scrollHeight > windowHeight &&
(body.offsetHeight <= windowHeight ||
html.offsetHeight <= windowHeight)) {
// DOMChange (throttle): fix height
var pending = false;
var refresh = function() {
if (!pending && html.scrollHeight != document.height) {
pending = true; // add a new pending action
setTimeout(function(){
html.style.height = document.height + 'px';
pending = false;
}, 500); // act rarely to stay fast
}
};
html.style.height = '';
setTimeout(refresh, 10);
addEvent("DOMNodeInserted", refresh);
addEvent("DOMNodeRemoved", refresh);
// clearfix
if (root.offsetHeight <= windowHeight) {
var underlay = document.createElement("div");
underlay.style.clear = "both";
body.appendChild(underlay);
}
}
// gmail performance fix
if (document.URL.indexOf("mail.google.com") > -1) {
var s = document.createElement("style");
s.innerHTML = ".iu { visibility: hidden }";
(document.getElementsByTagName("head")[0] || html).appendChild(s);
}
// disable fixed background
if (!fixedback && !disabled) {
body.style.backgroundAttachment = "scroll";
html.style.backgroundAttachment = "scroll";
}
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = +new Date;
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
directionCheck(left, top);
if (acceleration) {
var now = +new Date;
var elapsed = now - lastScroll;
if (elapsed < accelDelta) {
var factor = (1 + (30 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, accelMax);
left *= factor;
top *= factor;
}
}
lastScroll = +new Date;
}
// push a scroll command
que.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: +new Date
});
// don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function() {
var now = +new Date;
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < que.length; i++) {
var item = que[i];
var elapsed = now - item.start;
var finished = (elapsed >= animtime);
// scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / animtime;
// easing [optional]
if (pulseAlgorithm) {
position = pulse(position);
}
// only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// update last values
item.lastX += x;
item.lastY += y;
// delete and step back if it's over
if (finished) {
que.splice(i, 1); i--;
}
}
// scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY)
}
else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// clean up if there's nothing left to do
if (!left && !top) {
que = [];
}
if (que.length) {
requestFrame(step, elem, (delay / framerate + 1));
} else {
pending = false;
}
}
// start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* #param {Object} event
*/
function wheel(event) {
if (!initdone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// use default if there's no overflowing
// element or default action is prevented
if (!overflowing || event.defaultPrevented ||
isNodeName(activeElement, "embed") ||
(isNodeName(target, "embed") && /\.pdf/i.test(target.src))) {
return true;
}
var deltaX = event.wheelDeltaX || 0;
var deltaY = event.wheelDeltaY || 0;
// use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = event.wheelDelta || 0;
}
// scale by step size
// delta is 120 most of the time
// synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= stepsize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= stepsize / 120;
}
scrollArray(overflowing, -deltaX, -deltaY);
event.preventDefault();
}
/**
* Keydown event handler.
* #param {Object} event
*/
function keydown(event) {
var target = event.target;
var modifier = event.ctrlKey || event.altKey || event.metaKey ||
(event.shiftKey && event.keyCode !== key.spacebar);
// do nothing if user is editing text
// or using a modifier key (except shift)
// or in a dropdown
if ( /input|textarea|select|embed/i.test(target.nodeName) ||
target.isContentEditable ||
event.defaultPrevented ||
modifier ) {
return true;
}
// spacebar should trigger button press
if (isNodeName(target, "button") &&
event.keyCode === key.spacebar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -arrowscroll;
break;
case key.down:
y = arrowscroll;
break;
case key.spacebar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageup:
y = -clientHeight * 0.9;
break;
case key.pagedown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -arrowscroll;
break;
case key.right:
x = arrowscroll;
break;
default:
return true; // a key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
}
/**
* Mousedown event only for updating activeElement
*/
function mousedown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var cache = {}; // cleared out every once in while
setInterval(function(){ cache = {}; }, 10 * 1000);
var uniqueID = (function() {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
function setCache(elems, overflowing) {
for (var i = elems.length; i--;)
cache[uniqueID(elems[i])] = overflowing;
return overflowing;
}
function overflowingAncestor(el) {
var elems = [];
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(el)];
if (cached) {
return setCache(elems, cached);
}
elems.push(el);
if (rootScrollHeight === el.scrollHeight) {
if (!frame || root.clientHeight + 10 < rootScrollHeight) {
return setCache(elems, document.body); // scrolling root in WebKit
}
} else if (el.clientHeight + 10 < el.scrollHeight) {
overflow = getComputedStyle(el, "").getPropertyValue("overflow-y");
if (overflow === "scroll" || overflow === "auto") {
return setCache(elems, el);
}
}
} while (el = el.parentNode);
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||"").toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
que = [];
lastScroll = 0;
}
}
var requestFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(callback, element, delay){
window.setTimeout(callback, delay || (1000/60));
};
})();
/***********************************************
* PULSE
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// test
x = x * pulseScale;
if (x < 1) { // acceleartion
val = x - (1 - Math.exp(-x));
} else { // tail
// the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (pulseNormalize == 1) {
pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
addEvent("mousedown", mousedown);
addEvent("mousewheel", wheel);
addEvent("load", init);
Not sure what's going on here, but the issue with smoothscroll.js still stands. Disabling it seems to have no effect on the rest of my site though so I'm moving forward.

ipad/iphone carousel not working as expected with touchmove

I have a carousel that is working just fine for all browsers and all devices except for ipad/iphone. When I swipe the carousel, it will use jqueries easing and bounce several times before stopping. The only way to make it behave, as it does in all other browsers, is to have an alert message pop up after swiping, then it works perfectly.
[code]
$("#CarouselWrap").bind("touchmove", function(event){
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
whichWayMovingX[1] = event.originalEvent.touches[0].pageX;
whichWayMovingY[1] = event.originalEvent.touches[0].pageY;
}else{
whichWayMovingX[1] = event.originalEvent.changedTouches[0].pageX;
whichWayMovingY[1] = event.originalEvent.changedTouches[0].pageY;
}
if(whichWayMovingX[0] > whichWayMovingX[1]){
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
alert("left");
moveLeft();
}else{
moveLeft();
}
}else{
if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
alert("right");
moveRight();
}else{
moveRight();
}
}
});
[/code]
The moveLeft and moveRight functions are used with the arrows on the left and right of the carousel, so I know that these work, but only for onclick events.
[code]
switch(amountToMove) {
case -1011:
$("#CarouselFeed").animate({marginLeft: amountToMove},{duration: 'slow', easing: 'easeOutBack', wipe:'true'});
[/code]
Why would this code work so well for onclick, but not for touchmove?
I have tried to combine the binds of touchstart, touchend and touchmove - nada
I have tried to use touchmove mousemove - diddlesquat
I have tried to use a setTimeout thinking that I had to wait for the last event - nothing
Please help, this is driving me nuts.
Found the solution via some code for addressing the default behavior of a swipe.
First, set up the listeners:
if(document.getElementById("CarouselFeed")){
$("#CarouselFeed").bind("touchstart", function(event){
touchStart(event,"CarouselFeed")
});
$("#CarouselFeed").bind("touchend", function(event){
touchEnd(event);
});
$("#CarouselFeed").bind("touchmove", function(event){
touchMove(event);
});
}
I found the following code on a web site, that thanked two other web sites for their code and just as that web site changed the code a little to suit their needs, I have done the same:
// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM
// redefined a few things to make this applicable to our needs
// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
//
var touchStart = function(event,passedName){
// disable the standard ability to select the touched object
// event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.originalEvent.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if(fingerCount == 1){
// get the coordinates of the touch
startX = event.originalEvent.touches[0].pageX;
startY = event.originalEvent.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
}else{
// more than one finger touched so cancel
touchCancel(event);
}
}
var touchMove = function(event){
event.preventDefault();
if ( fingerCount == 1 ){
curX = event.originalEvent.touches[0].pageX;
curY = event.originalEvent.touches[0].pageY;
}else{
touchCancel(event);
}
}
var touchEnd = function(event){
// event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if (fingerCount == 1 && curX != 0){
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if(swipeLength >= minLength){
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
}else{
touchCancel(event);
}
}else{
touchCancel(event);
}
}
var touchCancel = function(event){
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
var caluculateAngle = function(){
var X = startX-curX;
deltaX = X;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if (swipeAngle < 0) {swipeAngle = 360 - Math.abs(swipeAngle);}
}
var determineSwipeDirection = function(){
if( (swipeAngle <= 45) && (swipeAngle >= 0) ){
swipeDirection = 'left';
}else if( (swipeAngle <= 360) && (swipeAngle >= 315) ){
swipeDirection = 'left';
}else if( (swipeAngle >= 135) && (swipeAngle <= 225) ){
swipeDirection = 'right';
}else if( (swipeAngle > 45) && (swipeAngle < 135) ){
swipeDirection = 'down';
}else{
swipeDirection = 'up';
}
}
var processingRoutine = function(){
var swipedElement = document.getElementById(triggerElementID);
if( swipeDirection == 'left' ){
moveLeft();
}else if( swipeDirection == 'right' ){
moveRight();
}else if( (swipeDirection == 'up') || (swipeDirection == 'left') ){
moveLeft();
}else if( (swipeDirection == 'up') || (swipeDirection == 'right') ){
moveRight();
}else if( (swipeDirection == 'down') || (swipeDirection == 'left') ){
moveLeft();
}else if( (swipeDirection == 'down') || (swipeDirection == 'right') ){
moveRight();
}
}
One note, I have this swipe working on a carousel that has banners. In order for the links for the banners to work, you have to comment out the event.preventDefault() within the touchStart and touchEnd functions.
And that is all it takes

Add swipe left/right to web page, but use default swipe up/down

I'm using padilicious to detect swiping gestures for web pages that will be viewed on iOS and desktops. It works great to swipe left/right for previous and next pages of my site. However, it seems to override the default behavior in iPhone/iPad when swiping up/down. I'd like an up/down swipe to scroll the page, which it does when I don't have padilicious running. Just having the code ignore up/down swipes doesn't seem to work.
The section of padilicious code that I've been
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
document.location = document.getElementById('nextPage').href;
} else if ( swipeDirection == 'right' ) {
document.location = document.getElementById('prevPage').href;
} else if ( swipeDirection == 'up' ) {
return;
} else if ( swipeDirection == 'down' ) {
return;
}
}
Remove event.preventDefault(); from all functions. In the function processingRoutine() {} add event.preventDefault(); for what you want.
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'orange';
event.preventDefault();
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'green';
event.preventDefault();
} else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'maroon';
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'purple';
}
}
there's a jquery library, which does the job (by not providing up/down methods): http://plugins.jquery.com/project/Touchwipe-iPhone-iPad-wipe-gesture
I'm not familiar with padilicious, but check and see if the ontouchmove="BlockMove(event);" is set anywhere, that prevents the page from scrolling like you describe, I'm not sure how you would get it to keep the vertical scrolling but swipe horizontally.
Edit: I've since found a really helpful overview for doing "native" feel iOS web apps, it might not be exactly what you're looking for, but could provide you with another avenue of approach to your problem. Check it out: http://matt.might.net/articles/how-to-native-iphone-ipad-apps-in-javascript/
Padilicious seems to be preventing default in all cases. See the call to event.preventDefault() in all cases.
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
You will have to change start, stop, ... handlers to not call preventDefault() in up and down cases.
I changed the script, this work:
// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM
// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
//event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
//event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
//event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
}
/* else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}*/
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
event.preventDefault();
swipedElement.style.backgroundColor = 'orange';
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
event.preventDefault();
swipedElement.style.backgroundColor = 'green';
}
/*else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
swipedElement.style.backgroundColor = 'maroon';
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
swipedElement.style.backgroundColor = 'purple';
}*/
}

Categories