I take it back, this code doesn't work on a touch device. It works fine with a mouse but not with actual touch.
Jan 29, 2023
4
Level 51
longpress vs click bloated code?
Alright Javascript friends,
This code does work, it distinguishes a longpress vs a click. But is there a better way? It just feels like a lot of code...
<input
@click="handleOnClick($event, $wire, {{ $item->id }})"
@mousedown="handleOnMouseDown"
@mouseup="handleOnMouseUp"
@touchstart="handleOnTouchStart"
@touchend="handleOnTouchEnd"
…
>
and
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('timerRef', false)
Alpine.store('action', '')
})
let isLongPress;
function handleOnClick(e, wire, itemId) {
if (isLongPress) {
wire.buyLater(itemId);
return;
}
Alpine.store.action = 'click';
wire.checkItem(itemId);
}
function handleOnMouseDown() {
startPressTimer();
}
function handleOnMouseUp() {
clearTimeout(Alpine.store.timerRef);
}
function handleOnTouchStart() {
startPressTimer();
}
function handleOnTouchEnd() {
if ( Alpine.store.action === 'longpress' ) return;
clearTimeout(Alpine.store.timerRef);
}
function startPressTimer() {
isLongPress = false;
Alpine.store.timerRef = setTimeout(() => {
isLongPress = true;
Alpine.store.action = 'longpress';
}, 500)
}
</script>
Please or to participate in this conversation.