-
-
Save kowach/406605216c105b0f9bcd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* swipeFunc as plugin | |
*/ | |
(function($) { | |
$.swipePlug = function(element, options) { | |
var defaults = { | |
touchstart: {x:-1, y:-1}, | |
touchmove : {y:-1, y:-1}, | |
touchend : false, | |
direction : "undetermined", | |
minLength: 40, | |
onSwipe: function(direction, length) {} | |
} | |
var plugin = this; | |
plugin.settings = { | |
} | |
var $element = $(element); | |
plugin.init = function() { | |
plugin.settings = $.extend({}, defaults, options); | |
$element.bind('touchstart',touchHandler); | |
$element.bind('touchmove',touchHandler); | |
$element.bind('touchend',touchHandler); | |
} | |
var touchHandler = function(event) { | |
var touch; | |
if (typeof event !== 'undefined'){ | |
event.preventDefault(); | |
if (typeof event.originalEvent.touches !== 'undefined') { | |
touch = event.originalEvent.touches[0]; | |
switch (event.type) { | |
case 'touchstart': | |
case 'touchmove': | |
plugin.settings[event.type].x = touch.pageX; | |
plugin.settings[event.type].y = touch.pageY; | |
break; | |
case 'touchend': | |
plugin.settings[event.type] = true; | |
var length = plugin.settings.touchstart.x - plugin.settings.touchmove.x; | |
if (plugin.settings.touchstart.x > -1 && plugin.settings.touchmove.x > -1 && Math.abs(length)>plugin.settings.minLength ) { | |
plugin.settings.direction = length<0 ? "right" : "left"; | |
// CALLBACK | |
plugin.settings.onSwipe( plugin.settings.direction, length ); | |
console.log(plugin.settings.direction, length); | |
} | |
default: | |
break; | |
} | |
} | |
} | |
} | |
plugin.init(); | |
} | |
$.fn.swipePlug = function(options) { | |
return this.each(function() { | |
if (undefined == $(this).data('swipePlug')) { | |
var plugin = new $.swipePlug(this, options); | |
$(this).data('swipePlug', plugin); | |
} | |
}); | |
} | |
})(jQuery); | |
// run on | |
$('.my-wrapper').swipePlug( { onSwipe:function(direction, length){ | |
// do stuff | |
} }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment