Search code examples
javascriptclicksettimeoutlong-press

how to implement longpress and click sepereate event in javascript?


I have a shooping cart icon for click or longpress. if user click on that, the ajax add the product to cart, and when user keep mouse down, the cart list apears.

here is the js code:

const shopping = document.getElementById('shopping');
shopping.addEventListener('mousedown' , function() {
    pressTimer = window.setTimeout(longpressed,1000);
});
shopping.addEventListener('mouseup' , function() {
    clearTimeout(pressTimer);
});

shopping.addEventListener('click' , function(e) {
    console.log('click');
    $.ajax({
        url: "{{route('user.cart.add' , $product->id)}}",
        method: 'get',
        data: {
            _token: '{{ csrf_token() }}',
            id: '{!! $product->id !!}'
        },
        success: function(quantity){
            $("#lblCartCount").html(quantity);
        }
    });
});

   function longpressed() {
    console.log('longpress');
    if(!$('#showFactor').is(':empty')){
        $('#showFactor').html('');
        $('#showFactor').hide();
    }else{
        $.ajax({
            url: "{{route('user.cart.index')}}",
            method: 'get',
            data: {
                _token: '{{ csrf_token() }}',
            },
            success: function(response){
                $('#showFactor').html(response);
                $('#showFactor').show();
            }
        });
    }
}

the question is how can I prevent click event after a long press ? problem is when the cartlist apeared, the product has been added to cart! I want the click to not fire when is a long press.


Solution

  • You can cancel the click event from propagating by hooking into the event capture phase.

    const shopping = document.getElementById('shopping');
    shopping.addEventListener('mousedown' , function() {
        pressTimer = window.setTimeout(longpressed,1000);
    });
    shopping.addEventListener('mouseup' , function(e) {
        clearTimeout(pressTimer);
    });
    
    shopping.addEventListener('click' , function(e) {
        console.log('click');
    });
    
    function longpressed() {
        console.log('longpress');
        
        window.addEventListener(
            'click',
            captureClick,
            true // <-- This registers this listener for the capture
                 //     phase instead of the bubbling phase!
        );
    }
    
    function captureClick(e) {
        e.stopPropagation(); // Stop the click from being propagated.
        window.removeEventListener('click', captureClick, true); // cleanup
    }
    <button type="button" id="shopping">
    Shopping cart
    </button>