Last active
February 15, 2021 09:59
-
-
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.
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
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; | |
} | |
}); | |
}] | |
}; | |
}]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@srfrnk what would the html look like?