Skip to content

Instantly share code, notes, and snippets.

@robmcalister
Last active January 3, 2016 04:59
Show Gist options
  • Save robmcalister/8413113 to your computer and use it in GitHub Desktop.
Save robmcalister/8413113 to your computer and use it in GitHub Desktop.
Tap and Hold directive for angularjs (rmHold).
app.directive('rmHold', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var isActive = false;
var currentTimeout = null;
var startCoords = {
x: null,
y: null
}
var moveCoords = {
x: 0,
y: 0
}
var getCoords = function(evt) {
var x = null;
var y = null;
if (evt.changedTouches && evt.changedTouches[0]) {
x = parseInt(evt.changedTouches[0].clientX);
y = parseInt(evt.changedTouches[0].clientY);
}
return {'x': x, 'y': y};
}
var validMove = function(beginCoords, endCoords) {
var validX = Math.abs(beginCoords.x - endCoords.x) < 20;
var validY = Math.abs(beginCoords.y - endCoords.y) < 20;
return validX && validY;
}
elem.on('touchstart', function($event) {
isActive = true;
startCoords = getCoords($event);
currentTimeout = $timeout(function() {
if (isActive) {
scope.$apply(attrs.rmHold);
}
}, 800);
});
elem.on('touchend touchcancel', function($event) {
endHold();
});
elem.on('touchmove', function($event) {
if (!isActive) {
return;
}
moveCoords = getCoords($event);
if (!validMove(startCoords, moveCoords)) {
endHold();
}
});
var endHold = function() {
isActive = false;
if (currentTimeout) {
$timeout.cancel(currentTimeout);
}
currentTimeout = startCoords = moveCoords = null;
}
}
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment