Skip to content

Instantly share code, notes, and snippets.

@mach3
Created September 4, 2013 12:38
Show Gist options
  • Select an option

  • Save mach3/6436356 to your computer and use it in GitHub Desktop.

Select an option

Save mach3/6436356 to your computer and use it in GitHub Desktop.
スワイプイベントを発火するやつを試作
(function($){
/**
* Detect supports
*/
$.support.touchEvents = "ontouchstart" in document;
$.support.msPointerEvents = window.navigator.msPointerEnabled;
/**
* Swipe event object
*/
$.swipeEvents = {
// Default options
options: {
EVENT_LEFT: "swipeleft", // Event name for swiping left
EVENT_RIGHT: "swiperight", // Event name for swiping right
threshold: 100 // threshold
},
// Return pageX position by event object
getPosition: function(e){
return /^touch/.test(e.type) ? e.touches[0].pageX : e.pageX;
},
// Handlers for touch*/MSPointer* events
handlers: {
// touchstart or MSPointerDown
start: function(e){
this._swipeStart = $.swipeEvents.getPosition(e);
},
// touchmove or MSPointerMove
move: function(e){
this._swipeDistance = $.swipeEvents.getPosition(e) - this._swipeStart;
},
// touchend or MSPointerUp
end: function(){
var $el, options;
$el = $(this);
options = this._swipeOptions;
if(this._swipeDistance > options.threshold){
$el.trigger(options.EVENT_RIGHT);
} else if(this._swipeDistance < options.threshold * -1){
$el.trigger(options.EVENT_LEFT);
}
}
},
// Event names
events: {
start: $.support.touchEvents ? "touchstart" : "MSPointerDown",
move: $.support.touchEvents ? "touchmove" : "MSPointerMove",
end: $.support.touchEvents ? "touchend" : "MSPointerUp"
}
};
/**
* Add swipe event
* @param Object options
*/
$.fn.setSwipeEvents = function(options){
if(! $.support.touchEvents && ! $.support.msPointerEvents){
return this;
}
options = $.extend({}, $.swipeEvents.options, options);
this.each(function(){
var el = this, $el = $(this);
el._swipeOptions = options;
if($.support.msPointerEvents){
$el.css("-ms-touch-action", "none");
}
$.each($.swipeEvents.events, function(type, name){
el.addEventListener(name, $.swipeEvents.handlers[type], false);
});
});
return this;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment