Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

webrobert's avatar

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>
0 likes
4 replies
webrobert's avatar

I take it back, this code doesn't work on a touch device. It works fine with a mouse but not with actual touch.

webrobert's avatar

@MohamedTammam, that code only handles the longpress (apparently it will work on touch, idk). My code handles both a click and a longpress. I just need make the touchscreen actually touch.

Please or to participate in this conversation.