Search code examples
jquerytouchjquery-events

How to detect the mouseup event after a mousemove and long touch?


Example: http://jsfiddle.net/za14jqw0/3/

HTML:

<div id="wrapper">
    <div id="a"></div>
</div>

CSS:

#a {
    width: 30px;
    height: 30px;
    background-color: red;
}

JavaScript:

$('#wrapper').on('mouseup', function() {
    $('#a').css('background-color', 'yellow');
});

The red box changes to yellow whenever there's a mouse up event.

The problem is that on touch devices, if the user touches the screen, move the finger around and wait a few seconds, the mouseup event is not fired.

How can I detect it?


Solution

  • To support touch devices you'll need 'touchend' too.

    MDN:

    The touchend event is fired when a touch point is removed from the touch surface.

    jQuery

    $('#wrapper').on('mouseup touchend', function() {
        $('#a').css('background-color', 'yellow');
    });
    

    FIDDLE

    Caveat:

    I can't find statistics regarding cross browser support, which is alarming considering the fluctuant nature of mobile browsers. If need be, you can use a libary such as jQuery mobile, which has an equivalent 'tap' event. Remember, you can select specific modules to download using the download builder to negate bloat.