Last active
July 29, 2020 04:39
-
-
Save cyrusfirheir/9b3f6305a7b90362d75bc155467e0b4b to your computer and use it in GitHub Desktop.
jQuery extension which adds a 'click/tap and hold' handler - For SugarCube 2
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
(function () { | |
"use strict"; | |
jQuery.fn.extend({ | |
holdDown: function holdDown(duration, handler) { | |
if (this.length === 0 || arguments.length === 0) return this; | |
if (arguments.length === 1) { | |
handler = arguments[0]; | |
duration = 1000; | |
} | |
var isCssTime = /[0-9\.]+m?s/; | |
duration = Number.isInteger(duration) ? duration : isCssTime.test(duration) ? Util.fromCssTime(duration) : 1000; | |
this.css({ | |
"--hold-duration": duration, | |
"--hold-passed": 0, | |
"--hold-percent": 0 | |
}); | |
var lc = 10; | |
var _this = this; | |
var held = function held() { | |
var _dur = Number(_this.css("--hold-duration")); | |
var _passed = Number(_this.css("--hold-passed")) + lc; | |
_this.css({ | |
"--hold-passed": _passed, | |
"--hold-percent": Math.floor(_passed / _dur * 100) + "%" | |
}); | |
}; | |
var clear = function clear() { | |
_this.css({ | |
"--hold-passed": 0, | |
"--hold-percent": 0 | |
}); | |
clearInterval(_this["hold-counter"]); | |
clearTimeout(_this["hold-timer"]); | |
}; | |
var fn = function fn() { | |
clear(); | |
_this["hold-counter"] = setInterval(held, lc); | |
_this["hold-timer"] = setTimeout(function () { | |
handler(); | |
clear(); | |
}, duration); | |
}; | |
this.on("mousedown", fn); | |
this.get(0).addEventListener("touchstart", fn, { | |
passive: true | |
}); | |
this.on("mouseup touchend", clear); | |
return this; | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment