Skip to content

Instantly share code, notes, and snippets.

@ahomu
Last active December 17, 2015 17:49
Show Gist options
  • Save ahomu/5648977 to your computer and use it in GitHub Desktop.
Save ahomu/5648977 to your computer and use it in GitHub Desktop.
タッチ操作に応じてクラスを付けたりハズしたり
/**
* FastClick and touch activation class control.
*
* @dependency jQuery or Zepto
* @author ahomu
*/
(function(win, doc, $) {
'use strict';
var Haster = function(options) {
options = $.extend({
el: doc,
pressedClass: 'is-pressed',
asBtnSelector : '[data-tap="btn"]',
asListSelector: '[data-tap="list"] > li'
}, options);
this.el = options.el,
this.$el = $(this.el);
this.timerId = null;
this.pressedClass = ' ' + options.pressedClass;
this.listSelector = options.asListSelector;
this.btnSelector = options.asBtnSelector;
// bind
this.btnHandler = $.proxy(this.btnHandler, this);
this.listHandler = $.proxy(this.listHandler, this);
this.$el.on('touchstart touchmove touchend touchleave touchcancel', this.btnSelector, this.btnHandler);
this.$el.on('touchstart touchmove touchend touchleave touchcancel', this.listSelector, this.listHandler);
};
Haster.prototype.btnHandler = function(evt) {
var that = this;
switch(evt.type) {
case 'touchstart':
evt.currentTarget.className += this.pressedClass;
break;
case 'touchmove':
case 'touchend':
case 'touchleave':
case 'touchcancel':
clearTimeout(this.timerId);
this.timerId = setTimeout(function() {
evt.currentTarget.className = evt.currentTarget.className.replace(that.pressedClass, '');
}, 150);
break;
}
};
Haster.prototype.listHandler = function(evt) {
var that = this;
switch(evt.type) {
case 'touchstart':
clearTimeout(this.timerId);
this.timerId = setTimeout(function() {
evt.currentTarget.className += this.pressedClass;
}, 150);
break;
case 'touchmove':
clearTimeout(this.timerId);
evt.currentTarget.className = evt.currentTarget.className.replace(this.pressedClass, '');
break;
case 'touchend':
case 'touchleave':
case 'touchcancel':
this.timerId = setTimeout(function() {
evt.currentTarget.className = evt.currentTarget.className.replace(that.pressedClass, '');
}, 150);
break;
}
};
Haster.prototype.destroy = function() {
this.$el.off('touchstart touchmove touchend touchleave touchcancel', this.btnSelector, this);
this.$el.off('touchstart touchmove touchend touchleave touchcancel', this.listSelector, this);
};
// export
if (typeof define === 'function' && define.amd) {
define(function() {
return Haster;
});
} else {
win.Haster = Haster;
}
})(window, document, $);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment