Skip to content

Instantly share code, notes, and snippets.

@srfrnk
Last active February 15, 2021 09:59
Show Gist options
  • Save srfrnk/9641a310d3e6092ca28b to your computer and use it in GitHub Desktop.
Save srfrnk/9641a310d3e6092ca28b to your computer and use it in GitHub Desktop.
angular directive: repeat action while mouse is clicked down for a long period of time and until the mouse is released.
define("directives/ngHold", ["app"], function (app) {
return app.directive('ngHold', [function () {
return {
restrict: "A",
link: function (scope, elm, attrs) {
},
controller: ["$scope", "$element", "$attrs", "$transclude", "$timeout", function ($scope, $element, $attrs, $transclude, $timeout) {
var onHold = function () {
return $scope.$eval($attrs.ngHold);
};
var onDone = function () {
return $scope.$eval($attrs.ngHoldDone);
};
var intervals = [];
($attrs.ngHoldInterval || "500").split(",").forEach(function (interval) {
intervals.push(interval.split(";"));
});
var timeout=null;
var intervalIdx;
var intervalCount;
function timeoutFoo() {
intervalCount++;
var max = intervals[intervalIdx].length == 1 ? 1 : intervals[intervalIdx][1];
if (intervalCount > max) {
intervalIdx = Math.min(intervalIdx + 1, intervals.length - 1);
intervalCount = 1;
}
timeout = $timeout(timeoutFoo, intervals[intervalIdx][0]);
onHold();
}
$element.on("mousedown", function (e) {
intervalIdx = 0;
intervalCount = 1;
timeout = $timeout(timeoutFoo, intervals[intervalIdx][0]);
$scope.$apply(onHold);
});
$element.on("mouseup", function (e) {
if (!!timeout) {
$timeout.cancel(timeout);
$scope.$apply(onDone);
timeout=null;
}
});
$element.on("mouseleave", function (e) {
if (!!timeout) {
$timeout.cancel(timeout);
$scope.$apply(onDone);
timeout=null;
}
});
}]
};
}]);
});
@tatsujb
Copy link

tatsujb commented Apr 10, 2018

@srfrnk what would the html look like?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment