Last active
March 9, 2022 11:11
-
-
Save rleroi/942b81cdc655433c5a70974c8579906c to your computer and use it in GitHub Desktop.
Mobile Longpress Directive for Vue
This file contains hidden or 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
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