Created
August 5, 2016 15:26
-
-
Save Mahabali/15152feac0e35677f96b8348f2f1017f to your computer and use it in GitHub Desktop.
Long Press Gesture Detection for ionic/Angular JS based frameworks
This file contains 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
// Example functions | |
$scope.itemOnLongPress = function(id) { | |
console.log('Long press'); | |
} |
This file contains 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
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) | |
}); | |
} | |
}); | |
} | |
}; | |
}) |
This file contains 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
<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