Skip to content

Instantly share code, notes, and snippets.

@rleroi
Last active March 9, 2022 11:11
Show Gist options
  • Save rleroi/942b81cdc655433c5a70974c8579906c to your computer and use it in GitHub Desktop.
Save rleroi/942b81cdc655433c5a70974c8579906c to your computer and use it in GitHub Desktop.
Mobile Longpress Directive for Vue
import debounce from 'lodash/debounce';
import Vue from 'vue';
// mobile longPress. usage: <div v-longpress="callbackFunction" /> you can specify an optional delay with v-longpress:1000="callbackFunction" (default is 300ms).
Vue.directive('longpress', {
bind(el, binding) {
let longPressTimeout = null;
el.addEventListener('touchstart', (e) => {
longPressTimeout = window.setTimeout(/*callback*/ binding.value, /*delay*/ binding.arg || 300);
});
el.addEventListener('touchend', () => {
window.clearTimeout(longPressTimeout);
});
el.addEventListener('touchcancel', () => {
window.clearTimeout(longPressTimeout);
});
el.addEventListener(
'touchmove',
debounce(
() => {
window.clearTimeout(longPressTimeout);
},
100,
{ maxWait: 100, leading: true, trailing: true }
)
);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment