Skip to content

Instantly share code, notes, and snippets.

@Mahabali
Created August 5, 2016 15:26
Show Gist options
  • Save Mahabali/15152feac0e35677f96b8348f2f1017f to your computer and use it in GitHub Desktop.
Save Mahabali/15152feac0e35677f96b8348f2f1017f to your computer and use it in GitHub Desktop.
Long Press Gesture Detection for ionic/Angular JS based frameworks
// Example functions
$scope.itemOnLongPress = function(id) {
console.log('Long press');
}
app.directive('onLongPress', function ($timeout) {
return {
restrict: 'A',
link: function ($scope, $elm, $attrs) {
var startTime, endTime;
$elm.bind('touchstart', function (evt) {
// Locally scoped variable that will keep track of the long press
$scope.longPress = true;
startTime = new Date().getTime() / 1000;
// We'll set a timeout for 2000 ms for a long press
$timeout(function () {
if ($scope.longPress) {
endTime = new Date().getTime() / 1000;
var difference = Math.floor(endTime - startTime);
if (difference > 1 && difference < 4) {
$scope.$apply(function () {
$scope.$eval($attrs.onLongPress);
});
}
}
}, 2000);
});
$elm.bind('touchend', function (evt) {
$scope.longPress = false;
// If there is an on-touch-end function attached to this element, apply it
if ($attrs.onTouchEnd) {
$scope.$apply(function () {
$scope.$eval($attrs.onTouchEnd)
});
}
});
}
};
})
<div class="someClass" on-long-press = "itemOnLongPress(someObject)"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment