I have written a plugin for jQuery which simulates mobile events, but with support for standard web browsers too. Here is the markup for the swipeleft and swiperight events:
(function($) {
var settings = {
swipe_h_threshold : 30,
swipe_v_threshold : 50,
taphold_threshold : 750,
startevent : ('ontouchstart' in document.documentElement) ? 'touchstart' : 'mousedown',
endevent : ('ontouchstart' in document.documentElement) ? 'touchend' : 'mouseup'
};
// swipeleft Event:
$.fn.swipeleft = function(handler) {
return this.each(function() {
$this = $(this);
var start_x = 0;
var end_x = 0;
$this.bind(settings.startevent, function(e) {
e.stopPropagation();
e.preventDefault();
start_x = e.pageX;
$this.one(settings.endevent, function(e) {
end_x = e.pageX;
if(start_x > end_x && (start_x - end_x >= settings.swipe_h_threshold))
{
handler.call(this);
}
});
});
});
};
// swiperight Event:
$.fn.swiperight = function(handler) {
return this.each(function() {
var $this = $(this);
var start_x = 0;
var end_x = 0;
$this.bind(settings.startevent, function(e) {
e.preventDefault();
e.stopPropagation();
start_x = e.pageX;
$this.one(settings.endevent, function(e) {
end_x = e.pageX;
if(start_x < end_x && (end_x - start_x >= settings.swipe_h_threshold))
{
handler.call(this);
}
});
});
});
};
}) (jQuery);
And I then call the events using the following:
$('#my_div').swiperight(function() { self.nextCard('r'); }); $('#my_div').swipeleft(function() { self.nextCard('r'); });
This seems to work fine on a desktop browser (well, Chrome anyway) > http://ben-major.co.uk/labs/carousel.html, but doesn't seem to function in Mobile Safari. The swipeleft executes without problem, but swiperight won't run whatsoever.
Can anyone offer any pointers?
If I'm not completely mistaken e (in the event callback) has an array touches on mobile browsers. It has one element for each touch event.
Here an example:
document.addEventListener('touchmove', function(event) {
event.preventDefault();
var touch = event.touches[0];
console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With